我想在用户点击谷歌地图时放置标记,下面是我的代码。它从-36.8484597,174.7633315
var map;
var myCenter = new google.maps.LatLng(-36.8484597,174.7633315);
function initialize()
{
var mapProp = {
center:myCenter,
zoom:2,
mapTypeId:google.maps.MapTypeId.ROADMAP
};
var map=new google.maps.Map(document.getElementById("map-canvas"),mapProp);
var marker=new google.maps.Marker({
position:myCenter,
});
marker.setMap(map);
// This event listener will call placeMarker() when the map is clicked.
google.maps.event.addListener(map, 'click', function(event) {
placeMarker(event.latLng);
});
}
function placeMarker(location) {
var marker = new google.maps.Marker({
position: location,
map: map
});
}
google.maps.event.addDomListener(window, 'load', initialize);
但是当我点击地图时,标记根本没有显示。有什么想法吗?
答案 0 :(得分:1)
您的地图变量是初始化函数的本地变量。它在placeMarker函数中不可用,除非你在初始化函数中传入或删除它之前的var关键字。
function initialize()
{
var mapProp = {
center:myCenter,
zoom:2,
mapTypeId:google.maps.MapTypeId.ROADMAP
};
map=new google.maps.Map(document.getElementById("map-canvas"),mapProp);
代码段:
var map;
var myCenter = new google.maps.LatLng(-36.8484597, 174.7633315);
function initialize() {
var mapProp = {
center: myCenter,
zoom: 2,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map-canvas"), mapProp);
var marker = new google.maps.Marker({
position: myCenter,
});
marker.setMap(map);
// This event listener will call placeMarker() when the map is clicked.
google.maps.event.addListener(map, 'click', function (event) {
placeMarker(event.latLng);
});
}
function placeMarker(location) {
var marker = new google.maps.Marker({
position: location,
map: map
});
}
google.maps.event.addDomListener(window, 'load', initialize);
html, body, #map-canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map-canvas" style="border: 2px solid #3872ac;"></div>