javascript - Google map 以特定搜索区域为中心

标签 javascript google-maps google-maps-api-3 geocoding

我在我的网站中使用 Google Maps api v.3。我想要实现的是以下流程:

  1. 用户会看到一个表单,他可以在其中输入地址(某种地址 - 城市、街道等)。
  2. 填写完表格后,系统会向他展示一张 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/

相关文章:

javascript - Vue 多选槽插入符下拉选项显示和隐藏

javascript - 谷歌地图和谷歌地图API给出了不同的纬度和经度

javascript - 谷歌地图地理编码不再免费?

ios - 将自定义信息窗口添加到 Google map

c# - Winforms、WebControl、谷歌地图和无效渲染

jquery - 如何将 Google Places API 绑定(bind)到仅限美国的地址?

javascript - 客户端 Google OAuth 2.0 在 Instagram 的 WebView 中停滞不前

javascript - 解析异步读取的 json 文件时 JSON 输入意外结束

javascript - 如何制作 HTML 表格第一列修复

angularjs - 使用 Google map API 服务回调函数创建 Angular 服务