我是新手,但我有一个谷歌V3地图,从用户的W3C浏览器地理编码信息中加载,我从地理编码对象中提取国家/地区,州和城市并更新输入框。如果用户输入街道地址,我想通过Google对其进行地理编码并更改map.setCenter和setZoom,并显示更新后的地图。当它工作时,我想添加一个标记和infowindow。尽管进行了数小时的研究和试验,但我无法获得地理编码和更新工作。 Chrome中的Developer Tool似乎表明在geocoder.geocode行停止/失败,下面以粗体显示。这是相关的代码。
var map, geocoder, marker, infowindow; //global variables
function initializeMap() {
// Try W3C Geolocation to geolocate desktop user
//initialize Google map, geolocate desktop user, and display after page loads
//find country, state, and city for the user's location - this all works
}
window.onload = initializeMap;
//change the Google Map after a user enters a street address
$("#streetAddress").blur(function() {
//if state, city and street address locations are present
if ( $(this).val().length > 0 && $("#state").val().length > 0 && $("#city3").val().length > 0 ) {
var gAddress = [$(this).val() + ", " + $("#city3").val() + ", " + $("#state").val()] ;
//get coordinates of this address
//if no geocode object exists, create one
if (!geocoder) {
geocoder = new google.maps.Geocoder(); //create Geocoder object else use existing one from initializeMap() ?
}
//create a GeocoderRequest object with user's street address
var geoCoderRequest = {address: gAddress}
//make a Geocoder request
geocoder.geocode( geoCoderRequest, function(results, status) { **//this line fails**
//check if status is OK
if ( status === google.maps.GeocoderStatus.OK) {
//update center of existing map on location returned for this address
map.setCenter(results[0].geometry.location);
map.setZoom(14);
}
});
} else {
return; //no action if gAddress is incomplete
}
});
答案 0 :(得分:1)
根据documentation,地址应该是一个字符串,但你已经将gAddress创建为一个数组。
尝试:
var gAddress = $(this).val() + ", " + $("#city3").val() + ", " + $("#state").val();
更新:响应您想要在地图初始加载后进行缩放(例如响应用户输入),这是一个简单的例子。
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map_canvas { height: 100% }
</style>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var map;
var start = 1;
function initialize() {
var homeLatlng = new google.maps.LatLng(51.476706,0); // London
var myOptions = {
zoom: 15,
center: homeLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}
function setZoom() {
map.setZoom(18);
}
function setTimedZoom() {
map.setZoom(start);
start = start+1;
if (start > 18) {
start = 1; // lets go round again and again; in reality you'd probably stop zooming at this point.
}
setTimeout(setTimedZoom, 3000);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<a href="javascript:setZoom()">Zoom In</a>
<a href="javascript:setTimedZoom()">Timed</a>
<div id="map_canvas"></div>
</body>
</html>