问题
Can't get a marker added, probably something very simple but I'm new to this. Thanks.
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?&sensor=true"></script>
<script type="text/javascript">
function addMarker() {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(-34.397, 150.644),
title:"Hello World!"
});
}
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(-34.397, 150.644),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map-canvas"),
mapOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);
$(document).ready(function() {
addMarker();
})
</script>
回答1:
Two issues, you need to set the map variable of the marker. Your map variable is local to the initialize function.
call the addMarker function from your initialize function (where the map exists), after the map is initialized.
function addMarker(map) { var marker = new google.maps.Marker({ position: new google.maps.LatLng(-34.397, 150.644), map:map, title:"Hello World!" }); } function initialize() { var mapOptions = { center: new google.maps.LatLng(-34.397, 150.644), zoom: 8, mapTypeId: google.maps.MapTypeId.ROADMAP }; var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions); addMarker(map); }
working example
回答2:
You have to set map property in marker constructor or invoke setMap on a new object:
var marker = new google.maps.Marker({
position: new google.maps.LatLng(-34.397, 150.644),
map: map, //make your map object global!
title:"Hello World!"
});
or
marker.setMap(map);
https://developers.google.com/maps/documentation/javascript/reference#Marker
EDIT: my comment about making map object global was apparently overlooked, so here it is:
map object is supposed to be global, not only for the sake of this solution, but you are going to need it in multiple functions in your script
来源:https://stackoverflow.com/questions/15413136/google-maps-cant-add-marker