Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
484 views
in Technique[技术] by (71.8m points)

javascript - Change color multiple marker in google maps API

I would like to ask about how to change color of a marker in google maps. The condition is, I have a program to create multiple markers in google maps. But how I can give specified color to each marker?

this is my code for now,

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

One way would be to pass the color into the addMarker function:

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

code snippet:

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...