Google maps GeoJSON- toggle marker layers?

2019-03-13 09:16发布

I have some GeoJSON returned from a call to a PostGIS database. I'd like to be able to add a marker for each feature, and be able to toggle different types of marker/feature. Currently I'm using JavaScript to generate a marker for each feature, adding them to arrays according to type, and then going through the arrays setting show/hide as appropriate to toggle the 'layers'.

This works OK, but I'm wondering if the new GeoJSON functionality offers a better way to do this. As far as I can see though, all the features get added to the same datalayer and toggling sets of them would involve either setting styles or just replacing with new, pre-filtered GeoJSON.

So the question is is it possible to have more than one data layer, and easily add/remove them from the map or am I better off looking at something like OpenLayers?

EDIT: Bit more research shows it's quite straightforward.

For each type of feature in the feature collection that we want to toggle on, create a new Data object. Add all the relevant features to that data object.

var datalayer = new google.maps.Data();
datalayer.addGeoJson(feature);
datalayer.setMap(mainmap);

Then store each data object/feature type as a key-value pair. On toggle, pull out the relevant data object and setMap as appropriate:

var datalayer= featuretypesobj["feature type to toggle"];
datalayer.setMap(mymap); //or
datalayer.setMap(null);

2条回答
\"骚年 ilove
2楼-- · 2019-03-13 10:01

You can also create separate layers

var layer_1 = new google.maps.Data();
var layer_2 = new google.maps.Data();

then populate it, e.g. with json data

layer_1.loadGeoJson('/path/to/data.json');
layer_2.loadGeoJson('/path/to/data2.json');

then add / remove them on the map

layer_1.setMap(map);
layer_2.setMap(map);
layer_1.setMap(null);
查看更多
祖国的老花朵
3楼-- · 2019-03-13 10:02

To Add: var layer_1 = new google.maps.Data(); should be done inside map initialization function, as:

var map;

  var data_layer_for_ramps;



  function initialize() {

            map = new google.maps.Map(document.getElementById('map'), {
              zoom: 12,
              center: new google.maps.LatLng(-33.897907, 151.179138),//-33.8151,151.0032 
              mapTypeId: 'roadmap'
            });

            data_layer_for_ramps = new google.maps.Data();
        }   
查看更多
登录 后发表回答