如何解决如果反应谷歌地图中没有活动位置,我会收到错误消息
我有一个代码,如果数组中有数据,该代码将自动放置标记并路由目的地。但是,如果数组为null,则会得到一个错误。即使我的阵列中没有数据,如何运行地图。
这是我的示例代码。
googlemap.js
<p>
<button onclick="myMove()">Click Me</button>
</p>
<div id="container">
<div id="animate"></div>
<div id="animate1"></div>
</div>
Map.js
import React,{ useState,useEffect } from 'react';
import {
withGoogleMap,GoogleMap,withScriptjs,Marker,DirectionsRenderer
} from "react-google-maps";
import "./config";
function MapDirectionsRenderer(props) {
const [directions,setDirections] = useState(null);
const [error,setError] = useState(null);
useEffect(() => {
const { places,travelMode } = props;
const waypoints = places.map(p => ({
location: { lat: p.latitude,lng: p.longitude },stopover: true
}));
const origin = waypoints.shift().location;
const destination = waypoints.pop().location;
const directionsService = new google.maps.DirectionsService();
directionsService.route(
{
origin: origin,destination: destination,travelMode: travelMode,waypoints: waypoints
},(result,status) => {
console.log(result)
if (status === google.maps.Directionsstatus.OK) {
setDirections(result);
} else {
setError(result);
}
}
);
});
if (error) {
return <h1>{error}</h1>;
}
return (
directions && (
<DirectionsRenderer directions={directions} />
)
);
}
const Map = withScriptjs(
withGoogleMap(props => (
<GoogleMap
defaultCenter={props.defaultCenter}
defaultZoom={props.defaultZoom}
>
{props.markers.map((marker,index) => {
const position = { lat: marker.latitude,lng: marker.longitude };
return <Marker key={index} position={position} />;
})}
<MapDirectionsRenderer
places={props.markers}
travelMode={google.maps.TravelMode.DRIVING}
/>
</GoogleMap>
))
);
export default Map;
如果只有两条路线(如果没有,则不会显示地图),地图将起作用。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。