Reputation: 3660
With Google's raster maps, I could create a map with an initial style like this (example taken from Google's documentation):
var mapStyles = [{ elementType: 'geometry', stylers: [{ color: '#242f3e' }]}];
var mapOptions = {
center: { lat: 40.674, lng: -73.945 },
zoom: 12,
styles: mapStyles
};
var map = new google.maps.Map(document.getElementById('map'), mapOptions );
Then, I could change the style like this:
var newStyles = [{ elementType: 'geometry', stylers: [{ color: '#ffffff' }]}];
map.setOptions({ styles: newStyles });
With the vector based maps, instead of specifying the style in code, I need to specify a map ID. That map ID will have a style that someone configured in the cloud. I created two of these map IDs (a normal theme and a dark them) following the instructions here, and then instantiated my map like this:
var mapOptions = {
center: { lat: 40.674, lng: -73.945 },
zoom: 12,
mapId: 'abcd1234mymapid'
};
var map = new google.maps.Map(document.getElementById('map'), mapOptions );
I tested both map IDs to be sure the theme was working. The problem is that I can't figure out how to change the map ID after creating the map. I want to allow the user to switch between map IDs. I tried:
// Does not work
map.setOptions({mapId: 'efgh5678myothermap'})
// Also does not work
map.mapId = 'efgh5678myothermap'
Is this functionality gone with Google's vector maps or am I doing it wrong?
I did make sure to include both map IDs when loading Google's script:
<script src="https://maps.googleapis.com/maps/api/js?key=KEY&v=weekly&callback=yourInitMapMethod&map_ids=abcd1234mymapid,efgh5678myothermap"></script>
Upvotes: 12
Views: 4900
Reputation: 614
Currently, the only workaround to switch from one style to another (changing mapIds) is to create a new map instance. Note that each map instance is billed. As per Dynamic Maps Usage and Billing. You can do something like this:
//Event that triggers change of map style
document.getElementById("map_id_1").addEventListener("click", function(){
mapID = "YOUR_MAP_ID"
new google.maps.Map(document.getElementById("map"), {
...sharedOptions,
mapId: mapID,
useStaticMap: false
});
});
Here's a complete JSFiddle sample you can try.
Dynamically changing the mapId through the setOptions()
function currently is not possible as it appears that mapId is not yet added as a property of the MapOptions interface as per the documentation.
I already filed a Feature Request in Google Maps Public issue tracker to support for this.
Upvotes: 14