繁体   English   中英

您如何使用 react google maps api 平移到您当前的位置

[英]How do you panTo your current location using react google maps api

我正在尝试使用按钮将谷歌地图平移到用户当前位置。 panTo 是有效的,但仅限于数值。 我尝试对地理位置返回的值使用 parseFloat 方法,但它不起作用。

我收到的错误是'不是具有有限坐标的 LatLng 或 LatLngLiteral:在属性 lat:NaN 不是可接受的值',名称:'InvalidValueError',堆栈:'Error\n'

const AddSpotPage = (props) => {
    const {isLoaded}= useJsApiLoader({
      googleMapsApiKey: process.env.REACT_APP_GOOGLE_MAPS_API_KEY,
    })

    const [map, setMap]= useState( /** @type google.maps.GoogleMap */ (null))

    **let userLat;
    let userLong;
    let test = {lat: parseFloat(userLat), lng: parseFloat(userLong)}**

    let center = {lat: 50.8584, lng: 12.2945}

    useEffect(()=> {
      navigator.geolocation.getCurrentPosition(position =>{
        userLat =             
          position.coords.latitude 
        ;
        userLong =             
           position.coords.longitude 
        ;
        console.log(userLat, userLong);
      })
    },[]);

return (
      <div className="pt-5 justify-content-center align-items-center d-flex w-100"
        style={{
          backgroundSize: "cover",
          height: "100vh",
        }}
      >

        <GoogleMap 
        center={center} 
        zoom={15} 
        mapContainerStyle={{width: "80%", height:"80%"}}
        onLoad={map=>setMap(map)}

        </GoogleMap>
        **<button onClick={()=> map.panTo(test)}>Pan Location</button>**

        
      </div>
    );
};

export default AddSpotPage;

这是对我有用的代码:

const[userLat, setUserLat]= useState();
const[userLong, setUserLong]= useState();

useEffect(()=> {
  navigator.geolocation.getCurrentPosition(position =>{
    setUserLat(position.coords.latitude);
    setUserLong(position.coords.longitude);
    console.log(userLat, userLong);
  })
},[]);
return(
<>
<GoogleMap 
center={center} 
zoom={15} 
mapContainerStyle={{width: "80%", height:"80%"}}
onLoad={map=>setMap(map)}
>

</GoogleMap>
<button onClick={()=> map.panTo({lat:userLat,lng:userLong})}>Pan Location</button>
</>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM