Search code examples
javascriptgoogle-mapsgoogle-maps-api-3

set fill color marker google map


How can I use my last column to set the color of the marker?

  google.load("visualization", "1", {packages:["map"]});
  google.setOnLoadCallback(drawChart);
  function drawChart() {
    var data = google.visualization.arrayToDataTable([
      ['Lat', 'Long', 'Name', 'Color'],
      [0.001, 0.002, 'Test 1', '#56df23'],
      [0.003, 0.004, 'Test 2', '#0023f6']
    ]);
    
    
    var options = {
        
        showTip: true,
        useMapTypeControl: true
        
        
    };

    var map = new google.visualization.Map(document.getElementById('map_div'));
    
    
    
    map.draw(data, options);
  }

While googling and stackoverflowing, I found this related topic: Google Maps: set custom color for type of markers

But the solution I am looking for must have these properties:

  • colors are defined by users (= no use png images)
  • I want to use the default marker, not a circle

Solution

  • You can use Symbols

    function pinSymbol(color) {
        return {
            path: 'M 0,0 C -2,-20 -10,-22 -10,-30 A 10,10 0 1,1 10,-30 C 10,-22 2,-20 0,0 z',
            fillColor: color,
            fillOpacity: 1,
            strokeColor: '#000',
            strokeWeight: 2,
            scale: 1
        };
    }
    

    example fiddle

    screenshot of resulting map

    code snippet:

    var data = [
      /* ['Lat', 'Long', 'Name', 'Color'], */
      [47.5, -122.0, 'Test 1', '#56df23'],
      [47.6, -122.2, 'Test 2', '#0023f6'],
      [47.7, -122.1, 'Test 2', 'yellow']
    ];
    
    function initialize() {
      var latlng = new google.maps.LatLng(47.605, -122.333);
      var myOptions = {
        zoom: 10,
        center: latlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
      };
      var map = new google.maps.Map(document.getElementById("map_canvas"),
        myOptions);
      var marker = new google.maps.Marker({
        map: map,
        position: latlng,
        icon: pinSymbol('red')
      });
    
      for (var i = 0; i < data.length; i++) {
        var marker1 = new google.maps.Marker({
          map: map,
          position: new google.maps.LatLng(data[i][0], data[i][1]),
          icon: pinSymbol(data[i][3])
        });
      }
    }
    
    function pinSymbol(color) {
      return {
        path: 'M 0,0 C -2,-20 -10,-22 -10,-30 A 10,10 0 1,1 10,-30 C 10,-22 2,-20 0,0 z',
        fillColor: color,
        fillOpacity: 1,
        strokeColor: '#000',
        strokeWeight: 2,
        scale: 1
      };
    }
    
    google.maps.event.addDomListener(window, 'load', initialize);
    html,
    body,
    #map_canvas {
      height: 500px;
      width: 500px;
      margin: 0px;
      padding: 0px
    }
    <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
    <div id="map_canvas" style="width:750px; height:450px; border: 2px solid #3872ac;"></div>