该组件传入地址,然后使用另一个api获取纬度和经度。纬度和经度然后被传入google-map-react api,转换成地图。
但是我无法为地图设置自定义的中心坐标。我设置了fetchAddress函数,使用谷歌地理编码API检索特定地址的经纬度坐标。然而,当我记录defaultProps.center对象时,它显示了两个对象,一个是默认值(纬度:60,经度:30),另一个是正确值(例如,纬度:-33.9325244,经度:151.1787937)。
我想使用来自Geocoding API响应的正确经纬度值来设置地图中心。但是当我输入经纬度值时,它只能处理默认值:lat: 60, lng: 30.
以下是我的代码:
import { AppContainer, Title, Image } from './styledMapApp';
import { useEffect, useState } from 'react';
import GoogleMapReact from 'google-map-react';
import axios from 'axios';
const MapApp = ({ location }: { location?: string }) => {
const apiKey = 'mykey';
const [latitude, setLatitude] = useState<number>(60);
const [longitude, setLongitude] = useState<number>(30);
const testingAddress = 'Arrivals Hall, Sydney International Airport, NSW 2020'; const encodedAddress = encodeURIComponent(testingAddress);
const fetchAddress = async () => {
try {
const response = await axios.get(
`https://maps.googleapis.com/maps/api/geocode/json?address={${encodedAddress}&key=${apiKey}`
);
const address = response.data.results[0].geometry.location;
const currentLatitude = address.lat;
const currentLongitude = address.lng;
setLatitude(currentLatitude);
setLongitude(currentLongitude);
} catch (error) {
console.error(error);
} };
useEffect(() => {
fetchAddress(); }, []);
const defaultProps = {
zoom: 11, };
console.log(latitude);
console.log(longitude);
return (
<AppContainer>
<Title>MapApp</Title>
<div style={{ height: '30vh', width: '100%' }}>
<GoogleMapReact
bootstrapURLKeys={{ key: apiKey }}
defaultCenter={{ lat: latitude, lng: longitude }}
defaultZoom={defaultProps.zoom}
></GoogleMapReact>
</div>
</AppContainer> ); }; export default MapApp;
控制台上也是显示取到值的:
60. MapApp.tsx:36
30. MapApp.tsx:37
-33.9325244. MapApp.tsx:36
151.1793765. MapApp.tsx:37
我不知道哪里出了问题?提前感谢大家回复
你axios请求的url写的有问题 多了一个左括号
const response = await axios.get(
`https://maps.googleapis.com/maps/api/geocode/json?address=${encodedAddress}&key=${apiKey}`
);