昨天我发了一个问题,这个问题是通过排版更正解决的,但现在我遇到了一个令我困惑的问题。
我在地图上有一个自定义标记,使用一个符号作为图标,这样我就可以旋转它。当我初始化它时,我将旋转设置为0,并在某个时候调用updateMap()
函数,这将为标记提供一个新的旋转值。的确如此,我可以通过在控制台中打印标记和图标来看到旋转发生了变化,但是标记仍然坚定地指向了北方。
下面是我初始化和旋转标记的代码:
var map;
var marker;
function initMap(position) {
var map_div = document.getElementById("map");
map = new google.maps.Map(map_div, {
zoom: 14,
center: { lat: position.Latitude, lng: position.Longitude },
mapTypeId: 'terrain'
});
marker = new google.maps.Marker({
position: map.getCenter(),
map: map,
title: "MY MARKER",
icon: {
path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW,
scale: 4,
strokeColor: '#00F',
rotation: 0,
}
});
}
function updateMap() {
var bearing = 135;
console.log(bearing);
marker.icon.rotation = bearing;
console.log(marker);
}
控制台告诉我,标记的旋转已经改变了,但是标记本身并没有改变方向。
我尝试过的事物:
resize
事件marker.icon.rotation
后标记在updateMap()
处的旋转值变为0,但实际标记始终指向135)initMap()
函数末尾的旋转--这确实有效,这使我相信updateMap()
函数有一些不正确的地方。我不知道是什么,它仍然执行这个函数。在全局范围内记录标记还会告诉我旋转发生了变化。欢迎任何想法或建议。
发布于 2017-07-05 05:17:50
icon
对象没有文档化的google.maps.Marker属性(虽然它可能“工作”,但不建议使用无文档的属性)。使用文档化的setter和getter获取值,然后更改它,然后再次设置它:
function updateMap() {
var bearing = 135;
console.log(bearing);
var icon = marker.getIcon();
icon.rotation = bearing;
marker.setIcon(icon);
console.log(marker);
}
代码片段:
var map;
var marker;
function initMap(position) {
var map_div = document.getElementById("map");
map = new google.maps.Map(map_div, {
zoom: 14,
center: {
lat: position.Latitude,
lng: position.Longitude
},
mapTypeId: 'terrain'
});
marker = new google.maps.Marker({
position: map.getCenter(),
map: map,
title: "MY MARKER",
icon: {
path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW,
scale: 4,
strokeColor: '#00F',
rotation: 0,
}
});
}
function updateMap(bearing) {
var icon = marker.getIcon();
icon.rotation = bearing;
marker.setIcon(icon);
}
function initialize() {
initMap({
Latitude: 37.4419,
Longitude: -122.1419
});
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<input type="button" value="rotate" onclick="updateMap(parseInt(document.getElementById('rotation').value));" /><input id="rotation" value="135" />
<div id="map"></div>
发布于 2017-07-05 01:31:58
您只需将updateMap
函数更改为:
function updateMap() {
var bearing = 135;
console.log(marker.icon);
marker.icon.rotation = bearing;
marker.setMap(map);
console.log(marker.icon);
}
在更新选项后,marker.setMap(map);
重新添加到地图中。
JSFiddle:https://jsfiddle.net/q3wjrpdw/8/
https://stackoverflow.com/questions/44921022
复制相似问题