Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google maps GeoJSON- toggle marker layers?

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);
like image 542
user814425 Avatar asked Apr 11 '14 08:04

user814425


People also ask

How do I show GeoJSON on Google Maps?

You can load and display a GeoJSON file by calling the loadGeoJSON() method of the data object.


2 Answers

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);
like image 96
datafunk Avatar answered Oct 15 '22 01:10

datafunk


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();
        }   
like image 20
Anup Kumar Das Avatar answered Oct 15 '22 01:10

Anup Kumar Das