【问题标题】:Convert address into coordinates for Google Maps Local Context (Geocoding + Local Context Maps)将地址转换为 Google Maps Local Context 的坐标(地理编码 + Local Context Maps)
【发布时间】:2020-11-15 03:05:50
【问题描述】:

我正在尝试将 Google Maps Local Context 插入我的网站,并且我希望使用地址字符串(1234 Main St, City, State, USA)来居中并在我的地图上显示一个标记。

这是我在网站上显示简单地图的代码,但我需要帮助获取地址而不是坐标。

我必须使用 Geocoder,但我需要帮助将其与 Google Maps Local Context 地图联系起来。

let map;

function initMap() {
  const localContextMapView = new google.maps.localContext.LocalContextMapView({
    element: document.getElementById("map"),
    placeTypePreferences: ["restaurant", "tourist_attraction"],
    maxPlaceCount: 12,
  });
  const center = { lat: 37.4219998, lng: -122.0840572 };
  map = localContextMapView.map;
  new google.maps.Marker({ position: center, map: map });
  map.setOptions({
    center: center,
    zoom: 14,
  });
}

https://jsfiddle.net/cegytdj6/

代码 sn-p:*

let map;

function initMap() {
  const localContextMapView = new google.maps.localContext.LocalContextMapView({
    element: document.getElementById("map"),
    placeTypePreferences: ["restaurant", "tourist_attraction"],
    maxPlaceCount: 12,
  });
  const center = {
    lat: 37.4219998,
    lng: -122.0840572
  };
  map = localContextMapView.map;
  new google.maps.Marker({
    position: center,
    map: map
  });
  map.setOptions({
    center: center,
    zoom: 14,
  });
}
/* Always set the map height explicitly to define the size of the div
       * element that contains the map. */

#map {
  height: 100%;
}


/* Optional: Makes the sample page fill the window. */

html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}
<!DOCTYPE html>
<html>

<head>
  <title>Local Context Basic</title>
  <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
  <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap&libraries=localContext&v=beta" defer></script>
  <!-- jsFiddle will insert css and js -->
</head>

<body>
  <div id="map"></div>
</body>

</html>

【问题讨论】:

    标签: google-maps google-geocoder


    【解决方案1】:

    请参阅简单的geocoder example,了解如何在 Google Maps Javascript API v3 中使用地理编码器。 下面的代码将使用地理编码器返回“1600 Amphitheatre Parkway, Mountain View, CA”的坐标。

    let geocoder = new google.maps.Geocoder();
      geocoder.geocode({ address: "1600 Amphitheatre Parkway, Mountain View, CA" }, (results, status) => {
        if (status === "OK") {
          const center = results[0].geometry.location;
          map.setCenter(center);
      new google.maps.Marker({ position: center, map: map });
      map.setOptions({
        center: center,
        zoom: 14,
      });
    

    将其放入您现有的代码中:

    let map;
    
    function initMap() {
      const localContextMapView = new google.maps.localContext.LocalContextMapView({
        element: document.getElementById("map"),
        placeTypePreferences: ["restaurant", "tourist_attraction"],
        maxPlaceCount: 12,
      });
      map = localContextMapView.map;
      let geocoder = new google.maps.Geocoder();
      geocoder.geocode({
        address: "1600 Amphitheatre Parkway, Mountain View, CA"
      }, (results, status) => {
        if (status === "OK") {
          const center = results[0].geometry.location;
          map.setCenter(center);
          new google.maps.Marker({
            position: center,
            map: map
          });
          map.setOptions({
            center: center,
            zoom: 14,
          });
        } else {
          alert("Geocode was not successful for the following reason: " + status);
        }
      });
    }
    

    updated fiddle

    代码 sn-p:

    let map;
    
    function initMap() {
      const localContextMapView = new google.maps.localContext.LocalContextMapView({
        element: document.getElementById("map"),
        placeTypePreferences: ["restaurant", "tourist_attraction"],
        maxPlaceCount: 12,
      });
      map = localContextMapView.map;
      let geocoder = new google.maps.Geocoder();
      geocoder.geocode({
        address: "1600 Amphitheatre Parkway, Mountain View, CA"
      }, (results, status) => {
        if (status === "OK") {
          const center = results[0].geometry.location;
          map.setCenter(center);
          new google.maps.Marker({
            position: center,
            map: map
          });
          map.setOptions({
            center: center,
            zoom: 14,
          });
        } else {
          alert("Geocode was not successful for the following reason: " + status);
        }
      });
    }
    /* Always set the map height explicitly to define the size of the div
           * element that contains the map. */
    
    #map {
      height: 100%;
    }
    
    
    /* Optional: Makes the sample page fill the window. */
    
    html,
    body {
      height: 100%;
      margin: 0;
      padding: 0;
    }
    <!DOCTYPE html>
    <html>
    
    <head>
      <title>Local Context Basic</title>
      <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
      <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap&libraries=localContext&v=beta" defer></script>
      <!-- jsFiddle will insert css and js -->
    </head>
    
    <body>
      <div id="map"></div>
    </body>
    
    </html>

    【讨论】:

      【解决方案2】:

      好像您已经有了地址,您只需要使用地理编码 API 将地址转换为坐标。 在您的脚本中,您需要通过重新加载页面来获取地理编码 API CDN。我将使用 axios 来做到这一点。这是代码; 在 HTML 页面的头部添加这两行。

      <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
      
      <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
      

      现在您可以使用 axios 发出 AJAX 请求。 在你的脚本里面;

      axios.get(`https://maps.googleapis.com/maps/api/geocode/json?address=Your_address&key=YOUR_API_KEY`)
           .then(response => {
             var lt = response.geometry.location.lat;
             var ln = response.geometry.location.lng;
             map.setCenter({lat: lt, lng:ln});
             marker.setCenter({lat: lt, lng: ln});
            })
            .catch(error => {
            console.log(error) //or whatever you want
            })
      

      【讨论】:

      • 感谢您对 Irfan 的评论。我很难让它工作,但另一个帖子推荐了另一种有效的解决方案。再次感谢,我的朋友。
      • 谢谢!但是您仍然可以在任何地方使用 axios 来发出 AJAX 请求,而无需编写原始代码。如果有帮助,请点赞。谢谢!
      • 你绝对不需要那个。地理编码是一种服务,它是 JS API 的一部分,因此无需调用 Web 服务(并使用其他库来执行此操作......)。
      猜你喜欢
      • 1970-01-01
      • 2013-10-05
      • 1970-01-01
      • 1970-01-01
      • 2012-05-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-23
      相关资源
      最近更新 更多