【问题标题】:How to get address based on lat lang lng in react google map如何在反应谷歌地图中根据纬度 lng 获取地址
【发布时间】:2021-01-02 21:47:08
【问题描述】:

我有一张使用 react-google-map 插件渲染的地图。流程是拖动标记并根据标记位置获取 lat、lng 和地址。我只得到 lat 和 lng。怎么获取地址?

下面是我的代码。

import React from "react"
import { compose, withProps, lifecycle } from "recompose"
import { withScriptjs, withGoogleMap, GoogleMap, Marker } from "react-google-maps"
import "./config";

const MyMapComponent = compose(
    withProps({
        googleMapURL: "https://maps.googleapis.com/maps/api/js?key=AIzaSyDzzi_VBcf2Oef6LTViLU767UPNHlnIze4&libraries=geometry,drawing,places",
        loadingElement: <div style={{ height: `100%` }} />,
        containerElement: <div style={{ height: `400px` }} />,
        mapElement: <div style={{ height: `100%` }} />,
    }),
    lifecycle({
        componentWillMount() {
            const refs = {}

            this.setState({
                position: null,
                onMarkerMounted: ref => {
                    refs.marker = ref;
                },

                onPositionChanged: () => {
                    const position = refs.marker.getPosition();
                    
                    console.log(position.toString());
                }
            })
        },
    }),
    withScriptjs,
    withGoogleMap
)((props) =>
    <GoogleMap defaultZoom={8} defaultCenter={{ lat: -34.397, lng: 150.644 }}>
        {props.isMarkerShown && <Marker position={{ lat: -34.397, lng: 150.644 }} draggable={true} ref={props.onMarkerMounted} onPositionChanged={props.onPositionChanged} />}
    </GoogleMap>
    )

class custommap extends React.PureComponent {
    state = {
        isMarkerShown: false,
    }

    render() {
        return (
            <div>
                <MyMapComponent isMarkerShown={true} />
            </div>
        )
    }
}


export default custommap;

感谢任何帮助

【问题讨论】:

    标签: javascript reactjs google-maps next.js react-google-maps


    【解决方案1】:

    我刚刚想通了。我使用 react-geocode 插件。

      Geocode.fromLatLng(position.lat(), position.lng()).then(
                            response => {
                              const address = response.results[0].formatted_address;
                              console.log(address);
                            },
                            error => {
                              console.error(error);
                            }
                          );
    

    【讨论】:

      猜你喜欢
      • 2013-07-13
      • 1970-01-01
      • 2014-04-11
      • 2012-09-28
      • 1970-01-01
      • 1970-01-01
      • 2021-03-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多