如何将谷歌地图集成到我的 Reactjs 网络应用程序后获得"latitude"和"longitude"?



我正在制作一个 Reactjs 应用程序,我想在应用程序中显示谷歌地图......我想实现以下内容

(1(我的应用程序需要用户的权限来获取他的当前位置并获取"纬度"和"经度"并保存它们。

(2(用户选择地图上的标记,我想得到那些纬度和经度点。

首先是更重要的。请帮帮我。谢谢。

https://www.youtube.com/watch?v=4z4hxEHlsxc

我看了这个视频,这很有帮助,但他没有教(1(问题

请参阅我的 Codepen 示例。您可以完成第一个任务。对于第二个任务,请阅读文档。这很简单。链接如下。

标记文档

事件文档

另外,这个库非常擅长处理谷歌地图。 看一看。

class App extends React.Component {
  constructor(props) {
    super(props);
    this.map = null;
    this.marker = null;
    this.state = {
      currentLocation: {
        lat: 0.0,
        lng: 0.0
      }
    };
  }
  componentDidMount() {
    if (navigator && navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(pos => {
        const coords = pos.coords;
        this.setState({
          currentLocation: {
            lat: coords.latitude,
            lng: coords.longitude
          }
        });
        this.setPin(coords.latitude, coords.longitude)
      });
      this.map = new google.maps.Map(document.getElementById('map'), {
          center: {lat: -34.397, lng: 150.644},
          zoom: 8
        });
    }else{
      //TODO:
    }
  }
  setPin(lat, lng) {
    if(this.map) {
      this.map.setCenter({lat: lat, lng: lng});
      if(this.marker) {
        this.marker.setMap(null);
        this.marker = null;
      }
      this.marker = new google.maps.Marker({
        position: {lat: lat, lng: lng},
        map: this.map,
        title: 'Current Location'
      });
    }else{
      console.log("Map has not loaded yet")
    }
  }
  render() {
    return (
      <div class="app">
        {this.state.currentLocation.lat } / {this.state.currentLocation.lng}
        <div id="map"></div>
      </div>
    );
  }
}
ReactDOM.render(
    <App />,
  document.getElementById('main')
);

使用此库https://www.npmjs.com/package/react-geocode

import Geocode from "react-geocode";
/// set Google Maps Geocoding API for purposes of quota management
Geocode.setApiKey("xxxxxxxxxxxx");
Geocode.setLangu`enter code here`age("en");
// Get address from latidude & longitude.
Geocode.fromLatLng("48.8583701", "2.2922926").then(
  response => {
    const address = response.results[0].formatted_address;
    console.log(address);
  },
  error => {
    console.error(error);
  }
);
// Get latidude & longitude from address.
Geocode.fromAddress("Eiffel Tower").then(
  response => {
    const { lat, lng } = response.results[0].geometry.location;
    console.log(lat, lng);
  },
  error => {
    console.error(error);
  }
);

最新更新