javascript - Gmaps.js Route with Distance -
i'm using gmaps.js api in little project i'm building.
basically replicate google maps functionality i'm looking route & distance 1 address (can input/form fields). notice this demo, requires clicking on map, , doesn't show total distance or drive time?
any opinions on best way of parsing 2 addresses form, calculating route , drive time using gmaps.js api?
breaking parts need to:
- search form entered addresses , geocode them using geocoding api.
- use results geocoding calculate route.
- pull required data route , plot/display
for geocoding see example: 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 destination / end point
now have lat/long points.
you can take few approaches route, drawing can done example: 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 });
if call getroutes
instead of drawroute
should directionsresult
object: https://developers.google.com/maps/documentation/javascript/directions#directionsresults . transitdetails
object contains information on travel time end location in form of arrival time. each leg
contain duration , distance can add looping through them , access like:
foreach($directions->routes[0]->legs $leg) { $time+=$leg.duration.value $distance+=$leg.distance.value }
update:
was playing api - , excuse nested callbacks - here working example: 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; (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); } }); } } }); } } }); });
Comments
Post a Comment