Search code examples
javascriptjsongoogle-mapsgoogle-maps-api-3geojson

Display one map marker from GeoJson file


I have a page to display all markers on a single google map and use map.data.loadGeoJson to achieve this.

The markers link to their respective details page with the following:

map.data.addListener('click', function(event) { 
    var id = event.feature.getProperty('name');
    window.location.href = 'submission-details.php?submission_id='+id;
    });

(The property 'name' is a json file property and the ID for each submission).

I would like the details page to also show a map, but only with one marker relevant to that specific details page.

My json type is feature collection, so I think I need a way to target each feature from the collection, rather than just using map.data.loadGeoJson which displays them all.

Not sure where to go from here and struggled to find someone else asking the same question so any help appreciated!

UPDATE Thanks Duncan.

I added:

      map.data.loadGeoJson('../photo_share/upload/file.json', {},function() {
      map.data.getFeatureById(53);
      map.data.getFeatureById(53).getProperty('name');
      console.log(map.data.getFeatureById(53));
      console.log(map.data.getFeatureById(53).getProperty('name'));
    });
google.maps.event.addDomListener(window, "load", initMap3);

And it does display in console log, but how do I now use this to only display the one marker, because it currently displays all of them still.


Solution

  • The google.maps.Data class has a getFeatureById method. Given you're passing that id into the submission-details.php page, you should be able to use that to get just the single feature.

    You still need to use loadGeoJson, and wait until that's loaded before trying to access it; see Google Maps API: getFeatureById for feature collection not working

    Update: And then to stop the whole collection displaying, maybe something like this (completely untested)?

    map.data.loadGeoJson('../photo_share/upload/file.json', {}, function(features) {
        // get the feature you want:
        var feature = map.data.getFeatureById(53);
    
        // hide the current set:
        map.data.setMap(null);
    
        // wipe out all the current features:
        for (var i = 0; i < features.length; i++) {
            map.data.remove(features[i]);
        }
    
        // add the feature you want back in:
        map.data.add(feature);
    
        // display it:
        map.data.setMap(map);
    });