我对在我的网站上使用谷歌地图的概念相当陌生。我已经让这个脚本在我的网页的div 中加载特定位置。但是,所需的位置不会加载到我的页面中。
比如说,每当我们打开页面时,我想在div 中加载位置BIT Main Bldg Patna, Bihar, India 12 m E
。但是,结果并不准确,我们需要放大更多图层。
<!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: 400px; height: 300px;"></div>
<script type="text/javascript">
var address = 'BIT Main Bldg Patna, Bihar, India 12 m E';
var map = new google.maps.Map(document.getElementById('map'), {
mapTypeId: google.maps.MapTypeId.TERRAIN,
zoom: 8
});
var geocoder = new google.maps.Geocoder();
geocoder.geocode({
'address': address
},
function(results, status) {
if(status == google.maps.GeocoderStatus.OK) {
new google.maps.Marker({
position: results[0].geometry.location,
map: map
});
map.setCenter(results[0].geometry.location);
}
else {
// Google couldn't geocode this request. Handle appropriately.
}
});
</script>
</body>
</html>
您可以通过在此页面的输出文本框中输入BIT Main Bldg Patna, Bihar, India 12 m E
来看到确切的所需结果。这里有什么错误?
要使页面显示类似于链接到的页面上的地图,您需要更改在映射构造函数中提供的选项。将 zoom
属性更改为 15 或 16,将mapTypeId
更改为 google.maps.MapTypeId.ROADMAP
,您的地图看起来将更像您想象中的地图。
请尝试以下操作:
var map = new google.maps.Map(document.getElementById('map'), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
zoom: 15
});
我会重新组织你的标记。脚本应位于 head 部分或 </body>
标记之后,以便在浏览器 DOM 中正确加载所有元素后执行函数。
创建一个函数,例如
<script type="text/javascript">
function initialise()
{
var address = 'BIT Main Bldg Patna, Bihar, India 12 m E';
var map = new google.maps.Map(document.getElementById('map'), {
mapTypeId: google.maps.MapTypeId.TERRAIN,
zoom: 10 //to get to a desirable zoom level change this value
});
var geocoder = new google.maps.Geocoder();
geocoder.geocode({
'address': address
},
function(results, status) {
if(status == google.maps.GeocoderStatus.OK) {
new google.maps.Marker({
position: results[0].geometry.location,
map: map
});
map.setCenter(results[0].geometry.location);
}
else {
// Google couldn't geocode this request. Handle appropriately.
}
});
}
</script>
然后在 <body>
标记中,您应该使用 onload 事件来执行脚本。
<body onload="initialise()">