Using a Google Apps API Key with Distance Matrix

I am using the Google Distance Mapping API and the documentation says I need an API key (but I can use it without it.) I would like to be able to control the usage, but I don't understand how to set it up.

I have a valid browser app API key from the Google Developers Console, it's new, so I'm assuming it's a version 3 key.

I have added valid links in the console

I have <script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>

on my page

I am using code like this

function callback(response, status) {
    if (status!==google.maps.DistanceMatrixStatus.OK) {
        _googleError('Error was: ' + status);
    } else {
        var origins = response.originAddresses;

        for (var i = 0; i < origins.length; i++) {
            var results = response.rows[i].elements;
            for (var j = 0; j < results.length; j++) {
                    $("#calcDistance").val(results[j].distance.text);
               //Other stuff that works here
            }
        }
    }
}

function calculateDistances(start, end) {
    var service = new google.maps.DistanceMatrixService();
    service.getDistanceMatrix(
        {
            origins: [start],
            destinations: [end],
            travelMode: google.maps.TravelMode.DRIVING,
            unitSystem: google.maps.UnitSystem.IMPERIAL,
            avoidHighways: false,
            avoidTolls: false
        }, callback);
}

      

How everything works fine. When I try to add a key to things, head south. I tried

<script src="https://maps.googleapis.com/maps/api/js?key={MY_KEY}&v=3.exp"></script>

and

<script src="https://maps.googleapis.com/maps/api/js?key={MY_KEY}"></script>

bad luck. When I do any of these, I get an "Invalid URL" error, similar to this question .

I also tried adding key: {MY_KEY},

in calculateDistances()

- no luck with that.

Am I missing something obvious? (I feel like I)

UPDATE:

@ Dr.Molle's answer gave me what I was looking for. I have enabled "Google Maps JavaScript API v3" and changed <script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>

to <script src="https://maps.googleapis.com/maps/api/js?key={MY_KEY}&v=3.exp"></script>

Now I can view the activity in the developer console as I would like.

+3


source to share


1 answer


When you use the key when loading the maps-Javascript APIs, you must enable the Google Maps JavaScript API v3 inside the console.

The related documentation for the Webservice, the key related portion of this documentation is irrelevant when you request the DistanceMatrixService via javascript API.



You will find the correct documentation at https://developers.google.com/maps/documentation/javascript/distancematrix

+1


source







All Articles