Dracarys February 2016

Json Google maps matrix data with JS

I want to get the actual duration of a specific route on googlemaps. But i just dont quite get it. This is my code in JS so far:

$(document).ready(function Duration() {
    var d = new Date();
$.ajax({
    url: 'http://maps.googleapis.com/maps/api/distancematrix/json?origins=91058%20Haupt%20Str.%6+DE&destinations=91058%20Cauerstr.%208+DE&mode=driving&language=de-DE&sensor=false&traffic_model=best_guess&departure_time='+(d.getTime()+300000),
    dataType: "json"
}).done(function(data) {
        var dur = data.rows[0].elements[0].duration.text;
        $("#duration").text(dur);         
    });
});

in html I just want to display with

<div id="duration"></div>

Can you please help me?! :) Thanks anyways

Answers


Vinny M February 2016

To do this properly you will want to follow Google's docs. Cross-domain rules wont allow you to load the resources you are requesting. This code will work: https://jsfiddle.net/Lw3Ls4yd/

First you should register for a Google Maps API key: https://developers.google.com/maps/documentation/javascript/get-api-key

Then add this resource to your page, adding your key in the correct spot.

<script async defer src="https://maps.googleapis.com/maps/api/js?key'KEY HERE' type="text/javascript"></script>

Then this local JS will do the trick:

var distanceService = new google.maps.DistanceMatrixService();
var d= new Date();
distanceService.getDistanceMatrix({
    origins: [ "Cauerstra├če 8, 91058 Erlangen, Deutschland" ],
    destinations: [ "Hauptstra├če 6, 48607 Ochtrup, Deutschland" ],
    travelMode: google.maps.TravelMode.DRIVING,
    unitSystem: google.maps.UnitSystem.METRIC,
    transitOptions: {
            departureTime:d
        },
    durationInTraffic: true,
    avoidHighways: false,
    avoidTolls: false
},
function (response, status) {
    if (status !== google.maps.DistanceMatrixStatus.OK) {
        console.log('Error:', status);
    } else {
        console.log(response);
        $('#duration').text(response.rows[0].elements[0].duration.text);
    }
});

Post Status

Asked in February 2016
Viewed 2,524 times
Voted 5
Answered 1 times

Search




Leave an answer