打字稿错误:环境模块声明仅在文件中的顶级允许

发布于 2025-01-28 08:31:41 字数 1844 浏览 3 评论 0原文

目前正在尝试从Google服务获取数据。 我不确定在声明global时如何处理此错误。

链接到原始代码段: https:// https://stackblitz.com/edit/githit/githiit/githubblit/githubub -mge1vg?file = index.ts

如何解决此问题,为什么要遇到错误。
代码的这一部分引发了一个错误:

仅在文件中的最高级别允许环境模块声明。

 declare global {
    interface Window {
      initMap: () => void;
    }
  }
  window.initMap = initMap;

这是整个代码:

import {useEffect, useState} from 'react';

type Geocode = {
  data?: google.maps.GeocoderResult | null;
  loading: boolean;
  error: string | null;
};

export const useReverseGeoCoding = ({latitude, longitude}: {latitude: number; longitude: number}): Geocode => {
  const [geocode, setGeocode] = useState<Geocode>({loading: false, error: null});

  useEffect(() => {
    const geocodeLatLng = async (geocoder: google.maps.Geocoder) => {
      /// Hard Coded for now
      const latlng = {
        lat: 52.509865,
        lng: -0.118092,
      };

      geocoder
        .geocode({location: latlng})
        .then(response => {
          if (response.results[0]) {
            console.log('response:', response);
            setGeocode({data: response.results[0], loading: false, error: null});
          } else {
            console.log('No results found');
          }
        })
        .catch(error => console.log('Geocoder failed due to: ' + error));
    };
    const initMap = (): void => {
      const geocoder = new google.maps.Geocoder();
      geocodeLatLng(geocoder);
    };
    initMap();
  }, [latitude, longitude]);

  declare global {
    interface Window {
      initMap: () => void;
    }
  }
  window.initMap = initMap;

  return geocode;
};

Currently trying to fetch data from a google service.
I'm not sure how I should handle this error when declaring global.

Link to the original code snippet:https://stackblitz.com/edit/github-mge1vg?file=index.ts

How would solve this and why am I getting the error.
This part of the code throws an error:

An ambient module declaration is only allowed at the top level in a file.

 declare global {
    interface Window {
      initMap: () => void;
    }
  }
  window.initMap = initMap;

Here is the whole code:

import {useEffect, useState} from 'react';

type Geocode = {
  data?: google.maps.GeocoderResult | null;
  loading: boolean;
  error: string | null;
};

export const useReverseGeoCoding = ({latitude, longitude}: {latitude: number; longitude: number}): Geocode => {
  const [geocode, setGeocode] = useState<Geocode>({loading: false, error: null});

  useEffect(() => {
    const geocodeLatLng = async (geocoder: google.maps.Geocoder) => {
      /// Hard Coded for now
      const latlng = {
        lat: 52.509865,
        lng: -0.118092,
      };

      geocoder
        .geocode({location: latlng})
        .then(response => {
          if (response.results[0]) {
            console.log('response:', response);
            setGeocode({data: response.results[0], loading: false, error: null});
          } else {
            console.log('No results found');
          }
        })
        .catch(error => console.log('Geocoder failed due to: ' + error));
    };
    const initMap = (): void => {
      const geocoder = new google.maps.Geocoder();
      geocodeLatLng(geocoder);
    };
    initMap();
  }, [latitude, longitude]);

  declare global {
    interface Window {
      initMap: () => void;
    }
  }
  window.initMap = initMap;

  return geocode;
};

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

骄傲 2025-02-04 08:31:41

移动

declare global {
  interface Window {
    initMap: () => void;
  }
}

主函数有效,然后

  const initMap = () => {
    const geocoder = new google.maps.Geocoder();
    setGeocoder(geocoder);
  };
  window.initMap = initMap;

在文件中调用您将使用钩子,然后添加脚本标签以初始化Google API

 <script
      src={`https://maps.googleapis.com/maps/api/js?key=${your API key}&callback=initMap&v=weekly&libraries=geocoder`}
      defer
    ></script>

Moving

declare global {
  interface Window {
    initMap: () => void;
  }
}

Outside of the main function works, then calling

  const initMap = () => {
    const geocoder = new google.maps.Geocoder();
    setGeocoder(geocoder);
  };
  window.initMap = initMap;

Within the file you will use the hook, and add a script tag to initialize the Google API

 <script
      src={`https://maps.googleapis.com/maps/api/js?key=${your API key}&callback=initMap&v=weekly&libraries=geocoder`}
      defer
    ></script>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文