如何从 Google 版本地图中的拖动标记中获取格式化地址 [英] How to get the formatted address from a dragged marker in Google Version Maps

查看:23
本文介绍了如何从 Google 版本地图中的拖动标记中获取格式化地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我制作了一个 Google 地图,可以让您在文本字段中输入地址.然后它会导航到您在文本字段中输入的地址,并留下一个可拖动的标记,拖动时会显示纬度和经度以及地理定位地址.

我不想显示上面的地址,而是希望当您拖动标记时在底角显示标记的地址,而不是从文本字段中输入的地址.

我尝试了很多方法都无济于事.lonlat[0].formatted_address 是我尝试过的一些东西之一.

我从 谷歌

我的代码如下:

<头><meta name="viewport" content="initial-scale=1.0, user-scalable=no"/><meta http-equiv="content-type" content="text/html; charset=UTF-8"/><title>Google Maps JavaScript API v3 示例:简单地理编码</title><link href="http://code.google.com/apis/maps/documentation/javascript/examples/default.css" rel="stylesheet" type="text/css"/><script src="http://maps.google.com/maps/api/js?v=3.5&amp;sensor=false"></script><script type="text/javascript">var 地理编码器;无功地图;函数初始化(){地理编码器 = 新的 google.maps.Geocoder();var latlng = new google.maps.LatLng(-34.397, 150.644);var myOptions = {变焦:8,中心:latlng,mapTypeId: google.maps.MapTypeId.ROADMAP}map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);}函数代码地址(){var address = document.getElementById("address").value;geocoder.geocode({'地址':地址},函数(结果,状态){如果(状态 == google.maps.GeocoderStatus.OK){map.setCenter(results[0].geometry.location);var 标记 = 新的 google.maps.Marker({地图:地图,可拖动:真实,位置:结果[0].geometry.location});//Javascript//google.maps.event.addListener(marker, 'dragend', function(evt){document.getElementById('current').innerHTML = '<p>标记丢弃:当前纬度:' + evt.latLng.lat().toFixed(3) + '当前长度:' + evt.latLng.lng().toFixed(3) + '</p>';});google.maps.event.addListener(marker, 'dragstart', function(evt){document.getElementById('current').innerHTML = '<p>当前正在拖动标记...</p>';});google.maps.event.addListener(marker, 'dragend', function(evt){document.getElementById('info').innerHTML = '<p>地址:' + results[0].formatted_address + '</p>';});google.maps.event.addListener(marker, 'dragstart', function(evt){document.getElementById('info').innerHTML = '<p>当前正在拖动标记...</p>';});map.setCenter(marker.position);标记.setMap(地图);} 别的 {alert("地理编码失败,原因如下:" + status);}});}<style type="text/css">#控制{位置:绝对;底部:1em;左:100px;宽度:400px;z-index:20000;填充:0 0.5em 0.5em 0.5em;}HTML,正文,#map_canvas {边距:0;宽度:100%;高度:100%;}</风格><body onLoad="初始化()"><div id="控件"><input id="address" type="textbox" value="悉尼,新南威尔士州"><input type="button" value="Geocode" onClick="codeAddress()"><div id="current" style="background-color:white;">什么都没有...</div><div id="info" style="background-color:white;">地址:</div>

<div id="map_canvas"></div>

解决方案

您需要使用反向地理编码服务(如您链接到的示例中所示)来检索格式化的地址.

该示例中的此代码调用反向地理编码器并使用响应显示其返回的 formatted_address:

function geocodePosition(pos) {geocoder.geocode({纬度:位置},功能(响应){如果(响应&&响应.长度> 0){updateMarkerAddress(responses[0].formatted_address);} 别的 {updateMarkerAddress('无法确定此位置的地址.');}});}

这是调用它的dragend监听器:

 google.maps.event.addListener(marker, 'dragend', function() {updateMarkerStatus('拖动结束');geocodePosition(marker.getPosition());});

这是一个工作示例(将从反向地理编码器收到的地址放入信息窗口)

代码片段:

var geocoder;无功地图;var 标记;var infowindow = new google.maps.InfoWindow({大小:新的 google.maps.Size(150, 50)});函数初始化(){地理编码器 = 新的 google.maps.Geocoder();var latlng = new google.maps.LatLng(-34.397, 150.644);var mapOptions = {变焦:8,中心:latlng,mapTypeId: google.maps.MapTypeId.ROADMAP}map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);google.maps.event.addListener(map, 'click', function() {infowindow.close();});}函数 geocodePosition(pos) {geocoder.geocode({纬度:位置},功能(响应){如果(响应&&响应.长度> 0){标记.formatted_address = 响应[0].formatted_address;} 别的 {marker.formatted_address = '无法确定此位置的地址.';}infowindow.setContent(marker.formatted_address + "<br>坐标:" + marker.getPosition().toUrlValue(6));infowindow.open(地图,标记);});}函数代码地址(){var address = document.getElementById('address').value;geocoder.geocode({地址":地址},功能(结果,状态){如果(状态 == google.maps.GeocoderStatus.OK){map.setCenter(results[0].geometry.location);如果(标记){标记.setMap(null);如果(信息窗口)infowindow.close();}标记 = 新的 google.maps.Marker({地图:地图,可拖动:真实,位置:结果[0].geometry.location});google.maps.event.addListener(marker, 'dragend', function() {geocodePosition(marker.getPosition());});google.maps.event.addListener(marker, 'click', function() {如果(marker.formatted_address){infowindow.setContent(marker.formatted_address + "<br>坐标:" + marker.getPosition().toUrlValue(6));} 别的 {infowindow.setContent(address + "<br>坐标:" + marker.getPosition().toUrlValue(6));}infowindow.open(地图,标记);});google.maps.event.trigger(marker, 'click');} 别的 {alert('地理编码失败,原因如下:' + status);}});}google.maps.event.addDomListener(window, "load", initialize);

html,身体 {高度:100%;边距:0;填充:0;}#map_canvas {高度:100%;}@media 打印 {html,身体 {高度:自动;}#map_canvas {高度:650px;}}

<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></脚本><div><input id="address" type="textbox" value="悉尼,新南威尔士州"><input type="button" value="Geocode" onclick="codeAddress()">

<div id="map_canvas" style="height:90%;top:30px"></div>

I have made a Google map that lets you input an address into a text field. It then navigates you to the address that you entered into the text field and leaves a draggable marker that when dragged shows you the Lat and Long and The Geolocated Address.

I instead of displaying the above address, would like when you drag the marker to display in the bottom corner the Address of the Marker and the not the inputted address from the text field.

I have tried a number of methods to no avail. lonlat[0].formatted_address was amongst some of the things i tried.

I got my reference from Google

My code is below:

<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no"/>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps JavaScript API v3 Example: Geocoding Simple</title>
<link href="http://code.google.com/apis/maps/documentation/javascript/examples/default.css" rel="stylesheet" type="text/css" />
<script src="http://maps.google.com/maps/api/js?v=3.5&amp;sensor=false"></script>

<script type="text/javascript">
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,
    draggable: true,
    position: results[0].geometry.location

});
   // Javascript//
   google.maps.event.addListener(marker, 'dragend', function(evt){
   document.getElementById('current').innerHTML = '<p>Marker dropped: Current Lat: ' + evt.latLng.lat().toFixed(3) + ' Current Lng: ' + evt.latLng.lng().toFixed(3) + '</p>';
   });

   google.maps.event.addListener(marker, 'dragstart', function(evt){
   document.getElementById('current').innerHTML = '<p>Currently dragging marker...</p>';
   });

   google.maps.event.addListener(marker, 'dragend', function(evt){
   document.getElementById('info').innerHTML = '<p>Address:  ' + results[0].formatted_address + '</p>';
   });

   google.maps.event.addListener(marker, 'dragstart', function(evt){
   document.getElementById('info').innerHTML = '<p>Currently dragging marker...</p>';
   });



 map.setCenter(marker.position);
 marker.setMap(map);

  } else {
    alert("Geocode was not successful for the following reason: " + status);
    }
     });
        }
</script>

<style type="text/css">
#controls {
position: absolute;
bottom: 1em;
left: 100px;
width: 400px;
z-index: 20000;
padding: 0 0.5em 0.5em 0.5em;
}
html, body, #map_canvas {
        margin: 0;
        width: 100%;
        height: 100%;
}
</style>
</head>
<body onLoad="initialize()">
<div id="controls">
<input id="address" type="textbox" value="Sydney, NSW">

<input type="button" value="Geocode" onClick="codeAddress()">
<div id="current" style="background-color:white;">Nothing yet...</div>
<div id="info" style="background-color:white;">Address:</div>
</div>
</div>


<div id="map_canvas"></div>


</body>
</html>

解决方案

You need to use the reverse geocoding service (as demonstrated in the example you link to) to retrieve the formatted address.

This code from that example calls the reverse geocoder and uses the response to display the formatted_address that is returned by it:

function geocodePosition(pos) {
  geocoder.geocode({
    latLng: pos
  }, function(responses) {
    if (responses && responses.length > 0) {
      updateMarkerAddress(responses[0].formatted_address);
    } else {
      updateMarkerAddress('Cannot determine address at this location.');
    }
  });
}

This is the dragend listener that calls it:

  google.maps.event.addListener(marker, 'dragend', function() {
    updateMarkerStatus('Drag ended');
    geocodePosition(marker.getPosition());
  });

Here is a working example (puts the address received from the reverse geocoder in the infowindow)

code snippet:

var geocoder;
var map;
var marker;
var infowindow = new google.maps.InfoWindow({
  size: new google.maps.Size(150, 50)
});

function initialize() {
  geocoder = new google.maps.Geocoder();
  var latlng = new google.maps.LatLng(-34.397, 150.644);
  var mapOptions = {
    zoom: 8,
    center: latlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }
  map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
  google.maps.event.addListener(map, 'click', function() {
    infowindow.close();
  });
}

function geocodePosition(pos) {
  geocoder.geocode({
    latLng: pos
  }, function(responses) {
    if (responses && responses.length > 0) {
      marker.formatted_address = responses[0].formatted_address;
    } else {
      marker.formatted_address = 'Cannot determine address at this location.';
    }
    infowindow.setContent(marker.formatted_address + "<br>coordinates: " + marker.getPosition().toUrlValue(6));
    infowindow.open(map, marker);
  });
}

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);
      if (marker) {
        marker.setMap(null);
        if (infowindow) infowindow.close();
      }
      marker = new google.maps.Marker({
        map: map,
        draggable: true,
        position: results[0].geometry.location
      });
      google.maps.event.addListener(marker, 'dragend', function() {
        geocodePosition(marker.getPosition());
      });
      google.maps.event.addListener(marker, 'click', function() {
        if (marker.formatted_address) {
          infowindow.setContent(marker.formatted_address + "<br>coordinates: " + marker.getPosition().toUrlValue(6));
        } else {
          infowindow.setContent(address + "<br>coordinates: " + marker.getPosition().toUrlValue(6));
        }
        infowindow.open(map, marker);
      });
      google.maps.event.trigger(marker, 'click');
    } else {
      alert('Geocode was not successful for the following reason: ' + status);
    }
  });
}

google.maps.event.addDomListener(window, "load", initialize);

html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}

#map_canvas {
  height: 100%;
}

@media print {
  html,
  body {
    height: auto;
  }
  #map_canvas {
    height: 650px;
  }
}

<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div>
  <input id="address" type="textbox" value="Sydney, NSW">
  <input type="button" value="Geocode" onclick="codeAddress()">
</div>
<div id="map_canvas" style="height:90%;top:30px"></div>

这篇关于如何从 Google 版本地图中的拖动标记中获取格式化地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆