嗨,我有以下代码。正如文档所述,我已经在脚本中启动了我的谷歌地图。我想从代码中的其他脚本更新标记。我该怎么做?当标记更新时,它是实时的还是必须刷新页面?如果页面必须刷新,我该怎么做一些实时更新?
<!--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});
}
position
成员,请使用记录的setPosition
方法:
marker
没有记录的var city2 = {
lat: 27,
lng: 152
};
marker.setPosition(city2);
- 另一个问题是设置标记位置的代码在 API 加载之前运行,而创建映射的代码运行。 这可以像这样
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>