我在我的网站中使用 Google Maps api v.3。我想要实现的是以下流程:
- 用户会看到一个表单,他可以在其中输入地址(某种地址 - 城市、街道等)。
- 填写完表格后,系统会向他展示一张 map ,显示以他输入的地址为中心的 map 。然后他可以输入关键字来搜索 map 区域中的谷歌地点。
我停下来的是地址到 map 的转换。据我了解 v3 API,我应该用 LatLng 中心位置初始化 map - 但有城市名称左右我还不能这样做。我需要在文本地址和坐标之间进行某种翻译 - 例如,当我搜索“比佛利山庄”时,谷歌地图就是这样做的。我猜是某种逆转?我应该如何在 javascript API 中执行此操作?
或者是否有一个选项可以在 v3 嵌入式 map 中包含搜索栏?
最佳答案
您需要使用geocode
,如下所示
复制自 http://code.google.com/apis/maps/documentation/javascript/geocoding.html
var geocoder;
var map;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(-34.397, 150.644);
var myOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}
function codeAddress() {
var address = document.getElementById("address").value;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
然后您需要在单击按钮时调用 codeAddress()
函数
关于javascript - Google map 以特定搜索区域为中心,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9374678/