使用地理编码器使地址成为谷歌地图的中心
我正在尝试编写一个程序,查找某个地址的相应值 latLng,然后将其用于地图的中心。到目前为止,这是我的代码,但是我遇到的主要问题是从地理编码器获取返回的值。
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps Geocoding Demo</title>
<script src="http://maps.google.com/maps/api/js?sensor=false"
type="text/javascript"></script>
</head>
<body>
<div id="map" style="width: 700px; height: 700px"></div>
<script type="text/javascript">
var mapOptions = {
mapTypeId: google.maps.MapTypeId.TERRAIN,
center: new google.maps.LatLng(54.00, -3.00),
zoom: 4
};
var geocoder = new google.maps.Geocoder();
var address = '3410 Dr Martin Luther King Jr Blvd, New Bern, NC, US';
geocoder.geocode({'address': address}, function(results, status) {
if(status == google.maps.GeocoderStatus.OK)
{
var bounds = new google.maps.LatLngBounds();
document.write(bounds.extend(results[0].geometry.location));
map.fitBounds(bounds);
new google.maps.Marker(
{
position:results[0].geometry.location,
map: map
}
);
}
}
);
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
</script>
</body>
</html>
I'm trying to write a program that finds the respective values latLng for an address and then using that for the center of the map. Here is my code so far, however the main problem I am having is getting the values of back from the geocoder.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps Geocoding Demo</title>
<script src="http://maps.google.com/maps/api/js?sensor=false"
type="text/javascript"></script>
</head>
<body>
<div id="map" style="width: 700px; height: 700px"></div>
<script type="text/javascript">
var mapOptions = {
mapTypeId: google.maps.MapTypeId.TERRAIN,
center: new google.maps.LatLng(54.00, -3.00),
zoom: 4
};
var geocoder = new google.maps.Geocoder();
var address = '3410 Dr Martin Luther King Jr Blvd, New Bern, NC, US';
geocoder.geocode({'address': address}, function(results, status) {
if(status == google.maps.GeocoderStatus.OK)
{
var bounds = new google.maps.LatLngBounds();
document.write(bounds.extend(results[0].geometry.location));
map.fitBounds(bounds);
new google.maps.Marker(
{
position:results[0].geometry.location,
map: map
}
);
}
}
);
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
</script>
</body>
</html>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您想设置谷歌地图对象的边界。
有关 LatLngBounds 的详细信息
(可选)
map.fitBounds(bounds.getCenter())
如果LatLngBounds
中有多个latlng
you want to set the bounds on the google map object.
more info on LatLngBounds
optionaly you could do
map.fitBounds(bounds.getCenter())
if you have more than onelatlng
in theLatLngBounds
您想使用新的经纬度在地图上调用 setCenter()。在您尝试执行此操作之前,我还会创建地图。
You want to call setCenter() on the map with the new latlng. I would also create the map before you try to do this.