如何更改谷歌地图上标记的属性

时间:2016-06-03 08:39:59

标签: google-maps google-maps-api-3

我正在谷歌地图上创建一个标记

function initialize() {
var myLatlng = new google.maps.LatLng(-25.363882,131.044922);
var mapOptions = {
zoom: 6,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
 }

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

var marker = new google.maps.Marker({
position: myLatlng,
map: map,
draggable: true,
title: 'Hello World!',
type: 'point'
icon : blue.png  
});
}

现在,如果我想更改标记的位置,我可以使用

var lat=43.88632569, var lon=-83.53269589
var position = new google.maps.LatLng(lat, lon);
marker.setPosition(position);

我有什么方法可以更改现有标记的图标 喜欢

marker.seticon(green.png);

1 个答案:

答案 0 :(得分:0)

您的代码中存在语法错误(URL应该是一个字符串,并且您在MarkerOptions对象的属性之间缺少逗号)。完整有效的公开网址适用于我:

function initialize() {
  var myLatlng = new google.maps.LatLng(-25.363882, 131.044922);
  var mapOptions = {
    zoom: 6,
    center: myLatlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }

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

  var marker = new google.maps.Marker({
    position: myLatlng,
    map: map,
    draggable: true,
    title: 'Hello World!',
    type: 'point',
    icon: "http://maps.google.com/mapfiles/ms/micons/blue.png"
  });
  var blue = true;
  google.maps.event.addDomListener(document.getElementById('btn'), 'click', function() {
    if (blue) {
      marker.setIcon("http://maps.google.com/mapfiles/ms/micons/green.png");
      blue = false;
    } else {
      marker.setIcon("http://maps.google.com/mapfiles/ms/micons/blue.png");
      blue = true;
    }
  });
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map {
  height: 100%;
  width: 100%;
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<input id="btn" value="toggle color" type="button" />
<div id="map"></div>