Maps API v3 Colored markers to show values

http://stackoverflow.com/questions/27239365

by Alex Azuero

HTML

<script src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<div id="map-canvas"></div>

CSS

#map-canvas {
    height: 400px;
}

JavaScript

var map;

// Locations: title, lat, lng, price
var locations = [
    ['House 1', -33.890542, 151.274856, 94000],
    ['House 2', -33.923036, 151.259052, 150000],
    ['House 3', -34.028249, 151.157507, 12000],
    ['House 4', -33.800101, 151.287478, 56000],
    ['House 5', -33.950198, 151.259302, 190000]
];

var h = 0,
    l = 999999999,
    i;

// Find high and low values
for (i = 0; i < locations.length; i++) {

    if (locations[i][3] > h) {
        h = locations[i][3];
    }

    if (locations[i][3] < l) {
        l = locations[i][3];
    }
}

// Calculate percentage
for (i = 0; i < locations.length; i++) {

    // Red = 0, Green = 100
    locations[i][4] = 100 - parseInt(((locations[i][3] - l) * 100) / (h - l));
}

function initialize() {

    var mapOptions = {
        zoom: 9,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        center: new google.maps.LatLng(-33.890542, 151.274856)
    };

    map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

    for (i = 0; i < locations.length; i++) {

        addPoint(new google.maps.LatLng(locations[i][1], locations[i][2]), locations[i][4], locations[i][0]);
    }
}

function addPoint(point, number, title) {

    var icon = {
        path: "M-20,0a20,20 0 1,0 40,0a20,20 0 1,0 -40,0",
        fillColor: numberToColorRgb(number),
        fillOpacity: .8,
        anchor: new google.maps.Point(0, 0),
        strokeWeight: 0,
        scale: .5
    }

    var marker = new google.maps.Marker({
        position: point,
        map: map,
        draggable: false,
        icon: icon,
        title: title
    });
}

function numberToColorRgb(i) {

    var red = Math.floor(255 - (255 * i / 100));
    var green = Math.floor(255 * i / 100);
    return 'rgb(' + red + ',' + green + ',0)';
}

initialize();