从Google Maps API的单击或拖动事件获取坐标?


12

我已经制作了Google Version 3 Geocoder,我希望能够在拖动或单击标记时拾取标记的坐标。下面是我的代码:

<!DOCTYPE html>
<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

    });
  } 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>
<div id="map_canvas"></div>
</body>
</html>

我试图使用下面的代码来执行此操作,但它似乎不起作用。

       // 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>';
       });

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

 //HTML//
 <div id='map_canvas'></div>
 <div id="current">Nothing yet...</div>

对您要执行的操作有点模糊,但是在事件处理程序功能中,您可以使用它evt.latLng来获取坐标
Roy

嘿,@ Roy我想输入一个地址,然后在弹出窗口中获取坐标,就像我的例子一样。在我的示例中,您可以通过文本输入转到一个地址,然后拖动该点,我想在拖动该点时弹出坐标。以下示例很好,但我想输入一个地址?请你能帮我吗?
布莱克·洛伊兹德斯

Mapperz示例看起来不错。我已经有一段时间没有使用GM API了,您可能会在StackOverflow上得到更快的答案。
罗伊

Answers:


9

我为您整理了一个简单的功能:

function markerCoords(markerobject){
    google.maps.event.addListener(markerobject, 'dragend', function(evt){
        infoWindow.setOptions({
            content: '<p>Marker dropped: Current Lat: ' + evt.latLng.lat().toFixed(3) + ' Current Lng: ' + evt.latLng.lng().toFixed(3) + '</p>'
        });
        infoWindow.open(map, markerobject);
    });

    google.maps.event.addListener(markerobject, 'drag', function(evt){
        console.log("marker is being dragged");
    });     
}

并插入markerCoords(marker); 在标记声明下!


9

带坐标的拖动标记和地理编码器

在此处输入图片说明

https://gmaps-samples-v3.googlecode.com/svn-history/r49/trunk/draggable-markers/draggable-markers.html

完整代码:

    <html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<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').innerHTML = str;
}

function initialize() {
  var latLng = new google.maps.LatLng(-34.397, 150.644);
  var map = new google.maps.Map(document.getElementById('mapCanvas'), {
    zoom: 8,
    center: latLng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  });
  var marker = new google.maps.Marker({
    position: latLng,
    title: 'Point A',
    map: map,
    draggable: true
  });

  // Update current position info.
  updateMarkerPosition(latLng);
  geocodePosition(latLng);

  // Add dragging event listeners.
  google.maps.event.addListener(marker, 'dragstart', function() {
    updateMarkerAddress('Dragging...');
  });

  google.maps.event.addListener(marker, 'drag', function() {
    updateMarkerStatus('Dragging...');
    updateMarkerPosition(marker.getPosition());
  });

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

// Onload handler to fire off the app.
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
  <style>
  #mapCanvas {
    width: 500px;
    height: 400px;
    float: left;
  }
  #infoPanel {
    float: left;
    margin-left: 10px;
  }
  #infoPanel div {
    margin-bottom: 5px;
  }
  </style>

  <div id="mapCanvas"></div>
  <div id="infoPanel">
    <b>Marker status:</b>
    <div id="markerStatus"><i>Click and drag the marker.</i></div>
    <b>Current position:</b>
    <div id="info"></div>
    <b>Closest matching address:</b>
    <div id="address"></div>
  </div>
</body>
</html>

上面的链接不再有效-您可以在developers.google.com/maps/documentation/javascript/tutorial
Alvin
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.