地图标记位置

时间:2015-05-04 22:55:24

标签: javascript google-maps google-maps-api-3

我在谷歌地图API v3中使用以下功能。

当用户在某个位置拖放地图标记时,此位置/地址会显示在输入字段内。

如何让访问者在此输入字段中输入他们的位置,然后点击按钮将标记移动到所需位置?

这是javascript代码:

<script type="text/javascript">
var geocoder = new google.maps.Geocoder();              
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.');
}
});

}

function updateMarkerStatus(str) {
document.getElementById('markerStatus').innerHTML = str;
}

function updateMarkerPosition(latLng) {
document.getElementById('info').innerHTML = [
latLng.lat(),
latLng.lng()
].join(', ');
}

function updateMarkerAddress(str) {
document.getElementById('address').value = str;
}

function initialize() {

 var latLng = new google.maps.LatLng(34.02733457017991,-118.25942712402343);
 map = new google.maps.Map(document.getElementById('mapCanvas'), {
 zoom:8,
 center: latLng,
 zoomControlOptions: {
 style: google.maps.ZoomControlStyle.SMALL
 },
 mapTypeControl: false,
 streetViewControl: false,
 scrollwheel: false,
 mapTypeId: google.maps.MapTypeId.TERRAIN
 });

 var marker = new google.maps.Marker({
 position: latLng,
 title: 'Drag and Drop me anywhere',
 map: map,
 icon : 'markers/map_marker.png',
 draggable: true
 });



 updateMarkerPosition(latLng);
 geocodePosition(latLng);


 google.maps.event.addListener(marker, 'dragstart', function() {
 updateMarkerAddress('Locating...');
 });

  google.maps.event.addListener(marker, 'drag', function() {

  updateMarkerPosition(marker.getPosition());
  });

  google.maps.event.addListener(marker, 'dragend', function() {

  geocodePosition(marker.getPosition());
  });
  }

  google.maps.event.addDomListener(window, 'load', initialize);             
 </script>

这是html代码:

<body>
<div id="mapCanvas"></div>
<div id="infoPanel">

<div class="row"><span class="label">Lat, Lon:</span>
<span id="info"></span></div>
<div class="row"><span class="label">Address:</span>
<input class="address-field" id="address"/>
<button class="button-locate" id="locate">Locate</button></div>
</div>
</body>

1 个答案:

答案 0 :(得分:0)

var geocoder = new google.maps.Geocoder();
var marker;
function geocodePosition(pos) {
geocoder.geocode({
     address: $("#idOfInput").val(),
}, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK){
          map.setCenter(results[0].geometry.location);
          marker.setPosition(results[0].geometry.location);
          updateMarkerAddress(results[0].formatted_address);
    } else {
          updateMarkerAddress('Cannot determine address at this location.');
    }
});

}

结果lat,地址lng你可以用它来设置标记的位置,试试这个代码;

{{1}}