5

I need to show a set of markers on a Google map. I know markers can be added directly on a Google map but given that I have 3 sets of markers, one for shops, one for parks and another one for hotels, how can I show them on 3 different layers and so that later on using javascript, I be able to hide one set of markers by doing sort of:

myLayer2.setMap(null);

I have checked Panoramio layer but it needs the images first to be uploaded to panoramio, but in my case for some particular security reason I cannot upload them to panoramio. I will have images locally and set those at runtime based upon some criteria.

Is there some way to do layer based work without using panoramio approach?

Faisal Mq
  • 5,036
  • 4
  • 35
  • 39
  • What does your existing code look like? What kind of [layers](https://developers.google.com/maps/documentation/javascript/layers) are you asking about? – geocodezip Apr 12 '14 at 18:14

1 Answers1

13

The Maps-API doesn't support this kind of custom layers(as you maybe know them from other map-API's like e.g. leaflet).

But it's not hard to achieve a similar feature.

You may use a google.maps.MVCObject. for every "layer" create a property for this MVCObject and set the value of this property to null or the google.maps.Map-instance( depending on the desired initial state of the "layer")

var myLayers=new google.maps.MVCObject();
    myLayers.setValues({parks:null,shops:null,hotels:map});
    //hotels initially are visible

When you want to add a Overlay...e.g. a Marker, to a "layer", bind the map-property of that Overlay to the related property of the MVCObject:

   parkMarker=new google.maps.Marker({/*options*/});
   parkMarker.bindTo('map',myLayers,'parks');

To toggle the display of all features within that "layer" you only need to set the property of the MVCObject:

//show the parks
myLayers.set('parks',map);
//hide the hotels
myLayers.set('hotels',null);

Demo: http://jsfiddle.net/doktormolle/UA85N/

Dr.Molle
  • 116,463
  • 16
  • 195
  • 201
  • Great answer Molle. I didn't know about MVCObject. Will dig deep into it now also. Thanks for your help. – Faisal Mq Apr 13 '14 at 09:06
  • Molle, how can I completely remove either the layer itself from the map or a set of markers (e.g parks) from the layer? – Faisal Mq Apr 24 '14 at 16:07
  • It's not a real layer(it's not a container with child-elements where removing the parent would remove the childs too). To remove all parks-markers you must call `myLayers.set('parks',null);` – Dr.Molle Apr 24 '14 at 21:33
  • Actually I want to remove all old markers from map/layer, whenever a new query is sent to server. I was asking only because of this requirement. – Faisal Mq Apr 25 '14 at 13:13