【发布时间】:2017-06-12 15:50:08
【问题描述】:
我正在使用 react-google-maps 包 https://github.com/tomchentw/react-google-maps 向 google maps javascript API 方向服务 https://developers.google.com/maps/documentation/javascript/examples/directions-simple 发出请求。我按预期从 API 获取响应并将其记录到浏览器,但我无法弄清楚如何让折线在地图组件中呈现。
这行代码
directionsDisplay.setMap(map);
正在返回
“InvalidValueError:setMap:不是地图方向的实例”。
所以我将其注释掉,因为似乎地图是通过将handleMapLoad() 通过 refs 传递给 GoogleMap 组件来设置的。非常感谢有关如何显示折线的一些指导。
/*global google*/
import React, { Component } from "react";
import { withGoogleMap, GoogleMap } from "react-google-maps";
const GettingStartedGoogleMap = withGoogleMap(props => (
<GoogleMap
ref={props.onMapLoad}
defaultZoom={5}
defaultCenter={{lat: 41.85, lng: -117.65}}
>
</GoogleMap>
));
export default class GettingStartedExample extends Component {
handleMapLoad = this.handleMapLoad.bind(this);
handleMapLoad(map) {
this.mapComponent = map;
if (map) {
console.log(map.getZoom());
}
const directionsService = new google.maps.DirectionsService();
const directionsDisplay = new google.maps.DirectionsRenderer();
// directionsDisplay.setMap(map);
const makeRequest = function() {
calculateAndDisplayRoute(directionsService, directionsDisplay);
};
function calculateAndDisplayRoute(directionsService, directionsDisplay) {
directionsService.route({
origin: 'San Francisco',
destination: 'Portland',
travelMode: 'DRIVING'
}, function(response, status) {
if (status === 'OK') {
directionsDisplay.setDirections(response);
console.log(response)
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
makeRequest();
}
render() {
return (
<div style={{height: `500px`}}>
<GettingStartedGoogleMap
containerElement={<div style={{ height: `100%` }} />}
mapElement={<div style={{ height: `100%` }} />}
onMapLoad={this.handleMapLoad}
/>
</div>
);
}
}
【问题讨论】:
标签: javascript google-maps reactjs