我有一个嵌入在我的网站上的谷歌 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模型的geometry属性中检索LAT/LNG:

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

Javascript相关问答推荐

当我使用jQuery时,我的图标显示为[对象对象]

使用Element.children在前后移动 node

TypScript:根据共享属性对项目进行分组并为其分配groupID

为什么(1 + Number.Min_UTE)等于1?

将下拉分区与工具提示结合起来

更改一组用户创建的项目的js排序标准

带对角线分隔符的图像滑动器

在shiny 模块中实现JavaScript

为什么我达到了时间限制!?LeetCode链接列表循环(已解决,但需要解释!)

按钮未放置在html dis位置

为什么我的includes声明需要整个字符串?

在Vite React库中添加子模块路径

如何将innerHTML字符串修剪为其中的特定元素?

如何发送从REST Api收到的PNG数据响应

同一类的所有div';S的模式窗口

如何在JAVASCRIPT中临时删除eventListener?

如何限制显示在分页中的可见页面的数量

将基元传递给THEN处理程序

使用RxJS from Event和@ViewChild vs KeyUp事件和RxJS主题更改输入字段值

使用Reaction窗体挂钩注册日历组件