Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove data from a Google Maps Data Layer?

I see Google Maps support geojson. Looking at the docs here: https://developers.google.com/maps/documentation/javascript/datalayer#load_geojson

Given the last example with the "Google", how can I make it such that I can click a button to add a new Geojson layer, and another button to toggle/remove the "Google" or even a letter? It seems to me that map.data appears to be a single layer, and is not multiple layers.

like image 409
Rolando Avatar asked Apr 14 '14 22:04

Rolando


People also ask

Can you remove points on Google Maps?

If you want to remove the pin from Google Maps, simply right click on it and select "Remove this destination." Poof, it's gone.


2 Answers

You are correct in that the Data Layer is a single layer. However, if you manually retrieve the GeoJSON and use the addGeoJson function instead of loadGeoJson you will get the added features returned. You can remove these later on.

So instead of

map.data.loadGeoJson('https://storage.googleapis.com/maps-devrel/google.json'); 

You can do something like this (this example uses jQuery to get the data and assumes there is a button with the ID removeBtn):

// Load the GeoJSON manually (works cross-origin since google sets the required HTTP headers) $.getJSON('https://storage.googleapis.com/maps-devrel/google.json', function (data) {   var features = map.data.addGeoJson(data);    // Setup event handler to remove GeoJSON features   google.maps.event.addDomListener(document.getElementById('removeBtn'), 'click', function () {     for (var i = 0; i < features.length; i++)       map.data.remove(features[i]);   });  });  

(See this JSbin for a working example you can play around with)

In more complex circumstances, you probably have to keep track of which datasource the user loaded and the features that got created because of that so you can delete them when requested.

like image 113
mensi Avatar answered Oct 06 '22 00:10

mensi


This worked for me:

map.data.forEach(function(feature) {     // filter...     map.data.remove(feature); }); 
like image 39
Irwin Avatar answered Oct 06 '22 01:10

Irwin