【发布时间】:2014-04-14 18:25:57
【问题描述】:
我已经从我的数据库表中提取了纬度和对数,并在带有标记的谷歌地图上显示了它。现在我想在点击标记时获取要在标记上显示的位置。我使用带有信息窗口的反向地理编码但是单击标记时无法获得预期的结果。当我调试它显示错误“未定义纬度”。错误在第 43 行,即 geocoder.geocode(....)。你能建议我应该如何进行吗?我还提供了可能对你有帮助的示例代码。请帮助我。
<?php
$dbname='140dev';
$dbuser='root';
$dbpass='root';
$dbserver='localhost';
$dbcnx = mysql_connect ("$dbserver", "$dbuser", "$dbpass");
mysql_select_db("$dbname") or die(mysql_error());
$sql = mysql_query("SELECT * FROM tweets");
$res = mysql_fetch_array($sql);
$lat_d = $res['geo_lat'];
$long_d = $res['geo_long'];
// mimic a result array from MySQL
$result = array(array('geo_lat'=>$lat_d,'geo_long'=>$long_d));
?>
<!doctype html>
<html>
<head>
<script type="text/javascript"
src="http://maps.googleapis.com/maps/api/js?key="API_key"&sensor=false"></script>
<script type="text/javascript">
var map;
var geocoder;
function initialize() {
geocoder = new google.maps.Geocoder();
// Set static latitude, longitude value
var latlng = new google.maps.LatLng(<?php echo $lat_d; ?>, <?php echo $long_d;?>);
// Set map options
var myOptions = {
zoom: 16,
center: latlng,
panControl: true,
zoomControl: true,
scaleControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
// Create map object with options
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
<?php
// uncomment the 2 lines below to get real data from the db
$result = mysql_query("SELECT * FROM tweets");
while ($row = mysql_fetch_array($result))
//foreach($result as $row) // <- remove this line
echo "addMarker(new google.maps.LatLng(".$row['geo_lat'].", ".$row['geo_long']."),
map);";
?>
}
function addMarker(latLng, map) {
var marker = new google.maps.Marker({
position: latLng,
map: map,
draggable: true, // enables drag & drop
animation: google.maps.Animation.DROP
});
var contentString = latLng.lat() + " - " + latLng.lng();
var infowindow = new google.maps.InfoWindow({
content: contentString
});
google.maps.event.addListener(marker, 'click', function() {
geocoder.geocode({'latLng': latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
map.setZoom(11);
infowindow.setContent(results[1].formatted_address);
infowindow.open(map, marker);
} else {
alert('No results found');
}
} else {
alert('Geocoder failed due to: ' + status);
}
});
});
}
</script>
</head>
<body onload="initialize()">
<div style="float:left; position:relative; width:550px; border:0px #000 solid;">
<div id="map_canvas" style="width:950px;height:700px;border:solid black 1px;">
</div>
</div>
</body>
</html>
【问题讨论】:
-
尝试位置:新 google.maps.LatLng(latLng);
-
它甚至没有显示之前代码至少显示的标记。还有其他选择吗?
-
声明 latlng 全局然后尝试...它的变量作用域问题
-
非常感谢。它成功了:)
标签: javascript php html google-maps google-maps-api-3