I wrote a little script that loads Google Maps tokens from a JSON file and puts them on a map. The script should be able to handle multiple instances. At the moment, the script looks like this (for testing, I used this JSON file ):
<div id="map" data-file="test.json" style="width: 200px; height: 200px; "></div>
<div id="map2" data-file="test2.json" style="width: 200px; height: 200px; "></div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
$(function() {
var googleMaps = function() {
var $el,
apiLoaded = false;
function init(el) {
$el = $(el);
loadData($el.data('file'));
};
function createMarker(data) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(data.lat, data.lng),
map: map,
title: data.title
});
}
function ready(data) {
var mapOptions = {
center: new google.maps.LatLng(58, 16),
zoom: 7,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map($el[0], mapOptions);
$.each(data, function(key, value) {
createMarker(value);
});
}
function loadAPI(callback) {
if (typeof google === 'object' && typeof google.maps === 'object') {
if(typeof(callback) === 'function') {
callback();
}
} else {
$.ajax({
url: 'http://www.google.com/jsapi/',
dataType: "script",
success: function() {
google.load('maps', '3', {
callback: function() {
if(typeof(callback) === 'function') {
callback();
}
},
other_params: 'sensor=false'
});
}
});
}
};
function loadData(file) {
$.ajax({
url: file,
success: function(data) {
var parsedJson = $.parseJSON(data);
loadAPI(function() {
ready(parsedJson);
});
},
error: function(request, status, error) {
console.log(error);
}
});
};
return {
init: init
}
}
});
</script>
This works if I have only .init()one instance, for example:
googleMaps().init(document.getElementById('map'));
But it fails as soon as I try a few instances:
googleMaps().init(document.getElementById('map'));
googleMaps().init(document.getElementById('map2'));
, , .loadAPI() google.load() , .loadAPI(), API Google , (Chrome Inspector: Uncaught TypeError: Object # "" (JS API Google)).
, AJAX .loadAPI() ? , true, . - , ?
.