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);
});
}