1

I am working on a small Chrome Extension that uses a content script to modify a page. The modification I want to do relies on the Google Maps API, and as such uses google.maps.DistanceMatrixService(). The problem is of course that the Google Maps API isn't loaded. I tried to just download the entire JS file and package it with my extension, but it doesn't work. Is there an easy way I could also load an external JS file with my extension?

I tried to manually create the script tag with the src pointing to the Google API, but I still get this error while running it:

Uncaught ReferenceError: google is not defined

The Google API allows a callback parameter in the url to call a function once the script finishes loading, but that also doesn't work since it can't find the function for some reason. See this error:

Uncaught InvalidValueError: runScript is not a function

Is there some way I can use the Google Maps API in my extension? I have googled and googled but can't find a way...

var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'http://maps.googleapis.com/maps/api/js?callback=runScript';
script.async = false;
head.appendChild(script);

function distance(ori, dest, cb) {
  var service = new google.maps.DistanceMatrixService();
  service.getDistanceMatrix(
  {
    origins: ori, //array of origins
    destinations: dest, //aray of destionations
    travelMode: google.maps.TravelMode.TRANSIT,
    unitSystem: google.maps.UnitSystem.METRIC,
    avoidHighways: false,
    avoidTolls: false
  }, cb);
}

function runScript() {
  distance(["location1"], ["location2"], function(response, status) {
    console.log(status);
  });
}
Andrew Myers
  • 2,754
  • 5
  • 32
  • 40
  • 1
    While it does not answer your question directly, you should look at [this question](https://stackoverflow.com/questions/9515704/building-a-chrome-extension-inject-code-in-a-page-using-a-content-script). It explains what happens when you add a ` – Xan Mar 03 '16 at 01:00
  • Have you check this SO ticket before? http://stackoverflow.com/questions/7896480/get-access-to-google-maps-api-from-a-chrome-extension. Discuss How to get access to Google Maps API from a Chrome extension – Android Enthusiast Mar 03 '16 at 14:10

0 Answers0