gpt4 book ai didi

javascript - 在谷歌地图 API 中更改颜色多标记

转载 作者:行者123 更新时间:2023-11-29 16:07:03 26 4
gpt4 key购买 nike

我想问一下如何更改谷歌地图中标记的颜色。条件是,我有一个程序可以在谷歌地图中创建多个标记。但是如何为每个标记指定指定的颜色?

这是我现在的代码,

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);

最佳答案

一种方法是将颜色传递给 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?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="map_canvas"></div>

关于javascript - 在谷歌地图 API 中更改颜色多标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38805138/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com