2016-08-06 237 views
0

我想問一下如何更改Google地圖中標記的顏色。條件是,我有一個程序在谷歌地圖中創建多個標記。但我如何給每個標記指定顏色?在Google地圖中更改顏色多標記API

這是我現在的代碼,

var markers = []; 
 
var map; 
 
var labels = 'ABCD'; 
 
var labelIndex = 0; 
 

 
function addMarker(location) { 
 
    var marker = new google.maps.Marker({ 
 
    position: location, 
 
\t \t label: labels[labelIndex++ % labels.length], 
 
\t \t icon: 'http://maps.google.com/mapfiles/ms/icons/green-dot.png' 
 
\t map: map 
 
\t }); 
 
    markers.push(marker);

+0

你是如何打算指定的顏色?您是否嘗試將顏色作爲參數添加到addMarker函數中? – geocodezip

回答

2

一種方式是將顏色傳遞到addMarker功能:

function addMarker(location, color) { 
    var marker = new google.maps.Marker({ 
    position: location, 
    label: labels[labelIndex++ % labels.length], 
    icon: 'http://maps.google.com/mapfiles/ms/icons/'+color+'.png', 
    map: map 
    }); 
    markers.push(marker); 
} 

proof of concept fiddle

enter image description here

代碼片段:

var markers = []; 
 
var map; 
 
var labels = 'ABCD'; 
 
var labelIndex = 0; 
 

 
function initialize() { 
 
    map = new google.maps.Map(
 
    document.getElementById("map_canvas"), { 
 
     center: new google.maps.LatLng(40.7127837, -74.0059413), 
 
     zoom: 11, 
 
     mapTypeId: google.maps.MapTypeId.ROADMAP 
 
    }); 
 
    // New York, NY, USA (40.7127837, -74.0059413) 
 
    // Newark, NJ, USA (40.735657, -74.1723667) 
 
    // Jersey City, NJ, USA (40.72815749999999, -74.07764170000002) 
 
    // Bayonne, NJ, USA (40.6687141, -74.11430910000001) 
 

 
    addMarker({ 
 
    lat: 40.7127837, 
 
    lng: -74.0059413 
 
    }, "red"); 
 
    addMarker({ 
 
    lat: 40.735657, 
 
    lng: -74.1723667 
 
    }, "green"); 
 
    addMarker({ 
 
    lat: 40.7281575, 
 
    lng: -74.0776417 
 
    }, "yellow"); 
 
    addMarker({ 
 
    lat: 40.6687141, 
 
    lng: -74.1143091 
 
    }, "orange"); 
 
} 
 
google.maps.event.addDomListener(window, "load", initialize); 
 

 

 
function addMarker(location, color) { 
 
    var marker = new google.maps.Marker({ 
 
    position: location, 
 
    label: labels[labelIndex++ % labels.length], 
 
    icon: { 
 
     url: 'http://maps.google.com/mapfiles/ms/icons/' + color + '.png', 
 
     labelOrigin: new google.maps.Point(15, 10) 
 
    }, 
 
    map: map 
 
    }); 
 
    markers.push(marker); 
 
}
html, 
 
body, 
 
#map_canvas { 
 
    height: 100%; 
 
    width: 100%; 
 
    margin: 0px; 
 
    padding: 0px 
 
}
<script src="https://maps.googleapis.com/maps/api/js"></script> 
 
<div id="map_canvas"></div>