嗨,我有以下代码。正如文档所述,我已在脚本中启动了我的谷歌地图。我想从代码中的不同脚本更新标记。我该怎么办?当标记更新它是否存在或页面是否必须刷新?如果页面必须刷新我怎么能这样做一些它实时更新?
<!--The div element for the map -->
<div id="map">
<% var getLat = lat %>
<% var getlong = long %>
<script>
// Initialize and add the map
function initMap() {
// The location of city
var passLat = <%= getLat %>;
var passLong = <%= getlong %>;
var city = {lat: passLat, lng: passLong};
// The map, centered at city
var map = new google.maps.Map(
document.getElementById('map'), {zoom: 10, center: city});
// The marker, positioned at Uluru
var marker = new google.maps.Marker({position: city, map: map});
}
</script>
<script
src="https://maps.googleapis.com/maps/api/js?key=MYAPI&callback=initMap" defer>
</script>
</div>
<h3 id = "LocalPhotos"> What the Local Area Looks Like:</h3>
<div id = "flick">
<script>
var city2 = {lat: 27, lng: 152};
marker.position(city2);
//update the marker here. But this code doesn't work
</script>
</div>
你有三个问题:
marker
变量是initMap
函数的局部变量。将其移至全局范围:// in global scope, outside the function
var marker;
function initMap() {
// The location of city
var passLat = <%= getLat %>;
var passLong = <%= getlong %>;
var city = {lat: passLat, lng: passLong};
// The map, centered at city
var map = new google.maps.Map(document.getElementById('map'),
{zoom: 10, center: city});
// The marker, positioned at Uluru
// initialize the global variable (remove the "var")
marker = new google.maps.Marker({position: city, map: map});
}
marker
没有记录的position
成员,使用记录的setPosition
方法:var city2 = {
lat: 27,
lng: 152
};
marker.setPosition(city2);
setTimeout
一样修复(但是这个问题应该在你的应用程序的上下文中解决,setTimeout是一个关于真正问题的绑定):var city2 = {
lat: 27,
lng: 152
};
setTimeout(function() {
marker.setPosition(city2);
map.setCenter(marker.getPosition());
//update the marker here. But this code doesn't work
}, 5000)
代码段:
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<!--The div element for the map -->
<div id="map">
<script>
var marker, map;
// Initialize and add the map
function initMap() {
// The location of city
var passLat = 37.4419;
var passLong = -122.1419;
var city = {
lat: passLat,
lng: passLong
};
// The map, centered at city
map = new google.maps.Map(
document.getElementById('map'), {
zoom: 10,
center: city
});
// The marker, positioned at Uluru
marker = new google.maps.Marker({
position: city,
map: map
});
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?callback=initMap" defer>
</script>
</div>
<h3 id="LocalPhotos"> What the Local Area Looks Like:</h3>
<div id="flick">
<script>
// the middle of the pacific ocean?
var city2 = {
lat: 27,
lng: 152
};
setTimeout(function() {
marker.setPosition(city2);
map.setCenter(marker.getPosition());
//update the marker here. But this code doesn't work
}, 5000)
</script>
</div>