问题描述
我有一个代码,如果数组中有数据,该代码将自动放置标记并路由目的地。但是,如果数组为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 (将#修改为@)