在我的Reactjs网络应用程序中集成谷歌地图后,如何获得“纬度”和“经度”?

问题描述 投票:0回答:1

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

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

要么

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

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

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

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

reactjs google-maps maps google-maps-markers react-map-gl
1个回答
0
投票

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

Markers documentation

Events documentation

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

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')
);
© www.soinside.com 2019 - 2024. All rights reserved.