我想使用Google Maps API指明方向,但不适用于地址。我曾尝试使用类似的地址解析服务,但它不知道“路线”(方向服务)。
我的方法:
var geocoder = new google.maps.Geocoder();
geocoder.geocode({'address': this.nomBar}, function(results, status) {
this.directionsService.route({
origin: this.currentLocation,
destination: results[0].geometry.location,
travelMode: 'DRIVING'
}, (response, status) => {
if (status === 'OK') {
that.directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
});
您无需使用地理编码器即可从起点和终点获取路线。 Google的documentation状态:
origin
(必填)指定要从其开始的位置计算路线。此值可以指定为String
(对于例如“芝加哥,伊利诺伊州”),作为LatLng
值或google.maps.Place
宾语。如果使用google.maps.Place
对象,则可以指定一个位置ID,查询字符串或LatLng
位置。
destination
(必填)指定要转到的结束位置计算路线。选项与原点字段相同如上所述。
此example使用地址:
directionsService.route({
origin: start, // e.g. "chicago, il"
destination: end, // e.g. "st louis, mo"
travelMode: 'DRIVING'
}, function(response, status) {
if (status === 'OK') {
directionsRenderer.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
虽然其他example使用坐标:
directionsService.route({
origin: {lat: 37.77, lng: -122.447},
destination: {lat: 37.768, lng: -122.511},
travelMode: google.maps.TravelMode[selectedMode]
}, function(response, status) {
if (status == 'OK') {
directionsRenderer.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
希望这会有所帮助!