点击Google Maps API并获取地址 [英] Click on Google Maps API and get the address

查看:308
本文介绍了点击Google Maps API并获取地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码允许在单击时获取坐标. 但是如何通过Google Maps API在地图上点击获取地址,城市名称,地区名称或国家/地区?

The following code allows to get the coordinates, on click. But how to get the address or city name or region name or country on click on the map, with Google Maps API?

var myLatlng = new google.maps.LatLng(41.38,2.18);
var myOptions = { zoom: 13, center: myLatlng}
var map = new google.maps.Map(document.getElementById("map-canvas"), myOptions);

google.maps.event.addListener(map, 'click', function(event) {alert(event.latLng);});

html, body, #map-canvas {
    height: 100%;
    width: 100%;
    margin: 0px;
    padding: 0px
}

<script src="https://maps.googleapis.com/maps/api/js?sensor=false&libraries=geometry,places&ext=.js"></script>
<div id="map-canvas"></div>

推荐答案

您可以将event.latLng穿过地理编码器以获取地址:

You can pass the event.latLng trough the Geocoder to get the address:

var myLatlng = new google.maps.LatLng(41.38, 2.18);
var myOptions = {
  zoom: 13,
  center: myLatlng
}
var map = new google.maps.Map(document.getElementById("map-canvas"), myOptions);
var geocoder = new google.maps.Geocoder();

google.maps.event.addListener(map, 'click', function(event) {
  geocoder.geocode({
    'latLng': event.latLng
  }, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      if (results[0]) {
        alert(results[0].formatted_address);
      }
    }
  });
});

小提琴

这篇关于点击Google Maps API并获取地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆