Jason Jason - 1 year ago 141
Javascript Question

Using a Google Apps API key with Distance Matrix

I am using the Google Distance Matrix API and the documentation tells me I need an API key (but I can use it without one.) I'd like to be able to monitor use but I'm stumped as to how to set it up.

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

I have added valid referers in the console

I have

<script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
on my page

I'm 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++) {
//Other stuff that works here

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

As it is things work just fine. When I try to add the key in things go south. I've tried

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


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

with no luck. When I do either of those I get an error about invalid URL, similar to this question.

I've also tried adding
key: {MY_KEY},
- no luck with that either.

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


@Dr.Molle's answer got me what I was looking for. I turned on "Google Maps JavaScript API v3" and changed
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
<script src="https://maps.googleapis.com/maps/api/js?key={MY_KEY}&v=3.exp"></script>
Now I can view activity in the Developer Console like I wanted.

Answer Source

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

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

The correct documentation you'll find at https://developers.google.com/maps/documentation/javascript/distancematrix

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download