javascriptvue.jsgoogle-mapsmaps

Google maps 3.54 adding style to the map


I'm currently working on a vue2 project with google maps 3.54 (latest version), this is required to use this version because of advancedMarkers.

https://maps.googleapis.com/maps/api/js?key=${this.mapKey}&callback=isMapLoad&libraries=marker&v=3.54

I read all the documentation about styling a map, and i have done it before on other version. But i do not find the way ir.

I try to set a style on the init:

this.map = new google.maps.Map(document.getElementById('map'), {
  mapId: 'GMAP_ID',
  language: this.$i18n.locale,
  center: this.defaultCoords,
  zoom: this.zoom,
  styles: [
  {
    featureType: 'water',
    elementType: 'all',
    stylers: [
     {
       color: '#f40000',
     },
     {
       visibility: 'on',
     },
    ],
  }
 ]
})

Or after the init with:

const styledMapType = new google.maps.StyledMapType(
 [
  {
    featureType: 'water',
    elementType: 'all',
    stylers: [
     {
       color: '#f40000',
     },
     {
       visibility: 'on',
     },
    ],
  }
 ]
)
this.map.mapTypes.set('styled_map', styledMapType)
this.map.setMapTypeId('styled_map')

// i have added to my script url the libraries maps to have StyledMapType

I got no error, but nothing change in both cases. What can i try?


UPDATE

There is a working example of the trouble: https://jsfiddle.net/981w4zxb/1/

If you remove the mapId like in the example, the style is apply, but in that case the markers doesn't work anymore.

If you add the mapid, the advanced markers is display, but the styles not apply.

I want both, it's mandatory too used advanced markers and styles without the cloud but legacy styles.


Solution

  • Not sure about how it is with Vue but your code looks correct – with or without &v=3.54.

    The thing is, if you instantiate your map with a mapId, the styles attribute in the constructor will not override the map's appearance.

    So, if you don't have cloud styling associated with your mapId, remove it from the constructor. Your styles should apply right away. And I suspect this.map.setMapTypeId(...) will take effect too.

    UPDATE

    You cannot use mapIds and styles at the same time. When you do, you'll get the warning:

    A Map's styles property cannot be set when a mapId is present. When a mapId is present, Map styles are controlled via the cloud console. Please see documentation at https://developers.google.com/maps/documentation/javascript/styling#cloud_tooling

    Given that your style definitions are stored in a DB, you'll likely need to create individual mapIds and their associated cloud style…

    Alternatively, you can reconsider your usage of Advanced Markers. Here's a guide to explore alternatives. Dislaimer: I wrote the guide.

    Finally, you might want to keep an eye on the gcloud cli which might, at some future point, let you programmatically create mapIds and styles -- just like Google did for API Keys.