我正在建立的一个小项目中使用Gmaps.js api。
基本上是要复制Google Maps功能,我希望获得从一个地址到另一个地址的路线和距离(可以只是输入/表单字段)。
我注意到this demo,但是它需要单击 map ,并且没有显示总距离或行车时间?
关于从表单中解析2个地址,然后使用gmaps.js api计算路线和行驶时间的最佳方法有何看法?
最佳答案
将其分为几部分,您需要:
有关地址解析,请参见以下示例:http://hpneo.github.io/gmaps/examples/geocoding.html
GMaps.geocode({
address: $('#Start').val(),
callback: function(results, status) {
if (status == 'OK') {
var latlng1 = results[0].geometry.location;
}
}
}); //Repeat for destination / end point
现在您有了经纬度。
然后,您可以采用几种方法进行布线,但是只需绘制即可,例如以下示例:http://hpneo.github.io/gmaps/examples/routes.html
map.drawRoute({
origin: [latlng1.lat(), latlng1.lng()],
destination: [latlng2.lat(), latlng2.lng()],
travelMode: 'driving',
strokeColor: '#131540',
strokeOpacity: 0.6,
strokeWeight: 6
});
如果调用
getRoutes
而不是drawRoute
,则应返回一个DirectionsResult
对象:https://developers.google.com/maps/documentation/javascript/directions#DirectionsResults。 TransitDetails
对象以到达时间的形式包含有关到达终点位置的旅行时间的信息。每个leg
还将包含一个持续时间和距离,您可以添加它们之间的循环并访问类似的内容:foreach($directions->routes[0]->legs as $leg) {
$time+=$leg.duration.value
$distance+=$leg.distance.value
}
更新:
正在使用API-并请嵌套嵌套的回调-这是一个有效的示例:http://jsfiddle.net/mdares/82Dp2/
jQuery(document).ready(function () {
var map;
var latlng1;
var latlng2;
GMaps.geocode({
address: $('#Start').val(),
callback: function (results, status) {
if (status == 'OK') {
latlng1 = results[0].geometry.location;
GMaps.geocode({
address: $('#End').val(),
callback: function (results, status) {
if (status == 'OK') {
latlng2 = results[0].geometry.location;
map = new GMaps({
div: '#map',
lat: latlng1.lat(),
lng: latlng1.lng(),
zoom: 12
});
map.drawRoute({
origin: [latlng1.lat(), latlng1.lng()],
destination: [latlng2.lat(), latlng2.lng()],
travelMode: 'driving',
strokeColor: '#131540',
strokeOpacity: 0.6,
strokeWeight: 6
});
map.getRoutes({
origin: [latlng1.lat(), latlng1.lng()],
destination: [latlng2.lat(), latlng2.lng()],
callback: function (e) {
var time = 0;
var distance = 0;
for (var i=0; i<e[0].legs.length; i++) {
time += e[0].legs[i].duration.value;
distance += e[0].legs[i].distance.value;
}
alert(time + " " + distance);
}
});
}
}
});
}
}
});
});