【发布时间】:2015-02-01 15:44:47
【问题描述】:
我正在使用 Javascript 在我的网站上呈现嵌入式 Google 地图画布。
渲染的输入是从数据库中检索的 lat/lng 坐标。但是,如果 lat/lng 返回 null,则地图将根据从数据库中检索到的相应地址字符串进行渲染。以下脚本始终为 lat/lng 坐标输入正确呈现,但不适用于地址输入。奇怪的是,当我多次刷新页面时,地址输入会随机工作。我试图消除这种随机性。认为我已经很接近了,但我似乎找不到丢失的链接。
注意:如果 lat/lng 为 null,则对 $lat 和 $lng 应用默认值,这样就不会弄乱下面的 JS。
如果有人能告诉我导致地址字符串随机呈现的以下代码有什么问题,我将不胜感激。
var map;
var marker;
var geocoder;
function initialize() {
var mapCanvas = document.getElementById('map-canvas');
var estLatLng = new google.maps.LatLng( <? php echo $lat; ?> , <? php echo $lng; ?> );
var mapOptions = {
center: estLatLng,
zoom: 17,
mapTypeId: google.maps.MapTypeId.ROADMAP,
disableDefaultUI: false,
streetViewControl: true,
scrollwheel: false
}
map = new google.maps.Map(mapCanvas, mapOptions);
marker = new google.maps.Marker({
position: estLatLng,
map: map,
draggable: false,
animation: google.maps.Animation.DROP,
title: "<?php echo $name;?>"
});
}
function toggleBounce() {
if (marker.getAnimation() != null) {
marker.setAnimation(null);
} else {
marker.setAnimation(google.maps.Animation.BOUNCE);
}
}
google.maps.event.addDomListener(window, 'load', initialize);
<? php
} ?>
$(".navbar").load("navbar.html", function() {
$("#navbarrestaurants").addClass("active");
});
$(document).ready(function() { <? php
if ($calcAddress) { ?> // this chunk of code is not loaded if lat/lng is not null
geocoder = new google.maps.Geocoder();
geocoder.geocode({
'address': "<?php echo $address;?>",
'componentRestrictions': {
country: 'Singapore'
}
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
}); <? php
} ?>
});
【问题讨论】:
-
在这些条件下浏览器看到的代码是什么样的?你能提供一个Minimal, Complete, Tested and Readable example 来证明这个问题吗?
-
您的浏览器中是否出现“地图未定义”错误?我认为您在“文档就绪”中的代码在“窗口加载”(这是定义地图的位置)之前执行。
标签: javascript php google-maps google-maps-api-3