簡體   English   中英

從谷歌獲取經緯度 map

[英]Fetch latitude and longitude from google map

我的網站中有一個嵌入式 Google map,它有一個“地點自動完成小部件”,我們在搜索時使用它來獲取地點 ID、名稱等。

我還需要得到一個標記的地方的緯度和經度。

function initMap() {
  const map = new google.maps.Map(document.getElementById("map"), {
    center: {
      lat: 11.0168,
      lng: 76.9558
    },
    zoom: 13,
  });

  const input = document.getElementById("pac-input");

  const autocomplete = new google.maps.places.Autocomplete(input, {
    fields: ["place_id", "geometry", "name", "formatted_address"],
  });

  autocomplete.bindTo("bounds", map);
  map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);

  const infowindow = new google.maps.InfoWindow();
  const infowindowContent = document.getElementById("infowindow-content");

  infowindow.setContent(infowindowContent);

  const geocoder = new google.maps.Geocoder();
  const marker = new google.maps.Marker({
    map: map
  });

  marker.addListener("click", () => {
    infowindow.open(map, marker);
  });
  autocomplete.addListener("place_changed", () => {
    infowindow.close();

    const place = autocomplete.getPlace();

    if (!place.place_id) {
      return;
    }

    geocoder.geocode({
      placeId: place.place_id
    }).then(({ results }) => {
      map.setZoom(11);
      map.setCenter(results[0].geometry.location);
      // Set the position of the marker using the place ID and location.
      // @ts-ignore TODO This should be in @typings/googlemaps.
      marker.setPlace({
        placeId: place.place_id,
        location: results[0].geometry.location,
      });
      marker.setVisible(true);
      infowindowContent.children["place-name"].textContent = place.name;
      infowindowContent.children["place-id"].textContent = place.place_id;
      infowindowContent.children["place-address"].textContent = results[0].formatted_address;
      infowindow.open(map, marker);
    }).catch((e) => window.alert("Geocoder failed due to: " + e));
  });
}

window.initMap = initMap;

您可以從您檢索的Place model 中的geometry屬性中檢索 lat/lng:

const place = autocomplete.getPlace();
var lat = place.geometry.location.lat();
var lng = place.geometry.location.lng();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM