Javascript 使用 jQuery 动态添加 Google Map V3 标记
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7844626/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Dynamically Add Google Map V3 Markers using jQuery
提问by Nyxynyx
I am adding markers to Google Maps dynamically using jquery and Google Maps V3 API. When the button search_button
is clicked, a request is sent to the server using AJAX, which returns a JSON array of LatLng corresponding to the results, which will be used to place the markers. However in my Javascript Conole, I get the error: Invalid value for property <map>: map
. Where did I go wrong? Here's my code:
我正在使用 jquery 和 Google Maps V3 API 动态地向 Google Maps 添加标记。当按钮search_button
被点击时,一个请求被使用AJAX,它返回经纬度的对应于该结果,这将被用于放置标记物的JSON数组发送到服务器。但是,在我的 Javascript 控制台中,我收到错误消息:Invalid value for property <map>: map
. 我哪里做错了?这是我的代码:
HTML Header JS:
HTML 标题 JS:
<script type="text/javascript">
function initialize() {
var latlng = new google.maps.LatLng(42.354183,-71.065063);
var options = {
zoom: 15,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), options);
}
</script>
jQuery
jQuery
$(function() {
$("#search_button").click(function(e){
e.preventDefault();
// Place markers on map
for( i = 0; i < json.length; i++) {
var latLng = new google.maps.LatLng(json[i].lat, json[i].lng);
var marker = new google.maps.Marker({
position: latLng,
map: map
});
}
});
});
});
回答by Jorge
you should make global your variable called map. That's all, in fact my recommendation it's to move all to a javascript file like this
您应该将名为 map 的变量设为全局变量。就是这样,实际上我的建议是将所有内容移动到这样的 javascript 文件中
$(document).ready(initialize);
var map;
function initialize() {
var latlng = new google.maps.LatLng(42.354183,-71.065063);
var options = {
zoom: 15,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map($('#map-canvas')[0], options);
$("#search_button").click(function(e){
e.preventDefault();
// Place markers on map
for( i = 0; i < json.length; i++) {
var latLng = new google.maps.LatLng(json[i].lat, json[i].lng);
var marker = new google.maps.Marker({
position: latLng,
map: map
});
}
});
}