Custom markers for points from a geoJson file with Google Maps

17,461

Use a styling-function(styling-functions enable you to apply styles based on a specific feature)

  map.data.setStyle(function(feature) {
    return {icon:feature.getProperty('icon')};
  });
Share:
17,461

Related videos on Youtube

doubleplusgood
Author by

doubleplusgood

Web Developer and Photographer in North Lincolnshire. Magento/ExpressionEngine/Rails. Working for @TheEnergyCell.

Updated on June 06, 2022

Comments

  • doubleplusgood
    doubleplusgood almost 2 years

    I'm using GeoJSON as a data source for Google Maps. I'm using v3 of the API to create a data layer as follows:

    <script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
    <script>
    var map;
    function initialize() {
    
      //Initialise the map
      var myLatLng = new google.maps.LatLng(53.231472,-0.539783);
      map = new google.maps.Map(document.getElementById('map-canvas'), {
        zoom: 17,
        center: myLatLng,
        scrollwheel: false,
        panControl: false,
        zoomControl: false,
        scaleControl: true,
        disableDefaultUI: true
      });
    
      //Initialise base folder for icons
      var iconBase = '/static/images/icons/';
    
      //Load the JSON to show places
      map.data.loadGeoJson('/api/geo');
    
    }
    
    google.maps.event.addDomListener(window, 'load', initialize);
    </script>
    
    <div id="map-canvas"></div>
    

    The source of my GeoJSON data is as follows:

    {
      "type": "FeatureCollection",
      "features": [
        {
          "type": "Feature",
          "geometry": {
            "type": "Point",
            "icon": "/static/images/icons/map-marker-do.png",
            "coordinates": [
              -0.53743,
              53.23437
            ]
          },
          "properties": {
            "name": "Cathedral",
            "description": "One of Europe’s finest Gothic buildings, once the tallest building in the world that dominates Lincoln's skyline.",
            "icon": "/static/images/icons/map-marker-do.png"
          }
        }
      ]
    }
    

    What I'm trying to do is make the marker icon on the map come from the "icon" property in the JSON, but cannot figure out how to get the data to change the default marker. Can anyone offer any advice? Thanks.

    • MrUpsidown
      MrUpsidown almost 10 years
      Where do you add the marker? What do you do with iconBase?
    • Dr.Molle
      Dr.Molle almost 10 years
      @MrUpsidown: he uses a data-layer, the features(e.g. markers/Points) loaded via loadGeoJson will be added automatically by the API
    • MrUpsidown
      MrUpsidown almost 10 years
      My bad. I saw that iconBase with part of the URL in the JSON and didn't think further :-)
    • geocodezip
      geocodezip almost 10 years
  • doubleplusgood
    doubleplusgood almost 10 years
    Sweet. Thanks so much. :)