У вас есть три вопроса:
- В настоящее время ваша переменная
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);
- Другая проблема заключается в том, что код, который устанавливает положение маркера, запускается до загрузки 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>