Load External Json File For Google Maps Styling
I'm currently succesfully styling my google maps using the JSON as made by this site. An example of my code is shown here (though in reality there are many hundreds of lines of jso
Solution 1:
Move the map creation into the loadJSON
callback function when/where the styles exist.
code snippet (note that the code snippet won't work on SO as the JSON file isn't available, the live example (external link above) works):
window.onload = functioninitMap() {
functionloadJSON(callback) {
var xobj = newXMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', 'style.json', true);
xobj.onreadystatechange = function() {
if (xobj.readyState == 4 && xobj.status == "200") {
callback(xobj.responseText);
}
};
xobj.send(null);
}
var loaded_json
loadJSON(function(response) {
// This correctly prints out the JSON
loaded_json = JSON.parse(response);
console.log(loaded_json)
var styledMapType = new google.maps.StyledMapType(loaded_json, {
name: 'Map'
});
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: {
lat: 51.529517,
lng: 10.058284
},
mapTypeControlOptions: {
mapTypeIds: ['satellite', 'styled_map']
}
});
//Associate the styled map with the MapTypeId and set it to display.
map.mapTypes.set('styled_map', styledMapType);
map.setMapTypeId('styled_map');
// This doesn'tconsole.log(loaded_json)
});
}
#map {
position: absolute;
top: 100px;
left: 0;
bottom: 100px;
right: 0;
}
<scripttype="text/javascript"src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDO1KU-C6Iy7VhyIJMEPiHNtqhWLmYCl3w&libraries=places"></script><divid="map"></div>
Solution 2:
You need to rearrange your code. It looks like the loaded_json is empty at the time the styledMapType is initialized. Try rearranging code as below:
var styledMapType;
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: {lat: 51.529517, lng: 10.058284},
mapTypeControlOptions: {
mapTypeIds: ['satellite', 'styled_map']
}
});
loadJSON(function(response) {
loaded_json = JSON.parse(response);
styledMapType = new google.maps.StyledMapType(loaded_json, {name: 'Map'});
map.mapTypes.set('styled_map', styledMapType);
map.setMapTypeId('styled_map');
});
Post a Comment for "Load External Json File For Google Maps Styling"