Google地图:在下拉列表中更改地图标记位置

时间:2016-03-20 07:39:08

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

我想根据下拉列表更改来更改地图标记位置,我正在做的是我得到lat,长时间下拉事件并想要将这些坐标传递给我当前的标记,这是我的代码

$("#location").change(function () {
    var addr = ($('#location').val());

    var geocoder = new google.maps.Geocoder();
    geocoder.geocode({ 'address': addr }, function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            alert("location : " + results[0].geometry.location.lat() + " " + results[0].geometry.location.lng());
            geoMarker.setMarkerOptions({
                duration: duration,
                easing: $('#easingOption').val()
            });
        } else {
            alert("Something got wrong " + status);
        }
    });
});

HTML:

<select id="location">
    <option>Dubai</option>
    <option>Sharjah</option>
</select>

它会提醒当前坐标,但我需要知道如何将这些坐标传递到我的标记位置

2 个答案:

答案 0 :(得分:0)

看起来您正在寻找.setPosition()

var latlng = new google.maps.LatLng(-24.397, 140.644);
marker.setPosition(latlng);

答案 1 :(得分:0)

您需要根据地理编码操作的结果设置标记的位置。

$("#location").change(function() {
  var addr = ($('#location').val());

  var geocoder = new google.maps.Geocoder();
  geocoder.geocode({'address': addr
  }, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      map.setCenter(results[0].geometry.location);
      geoMarker.setPosition(results[0].geometry.location);
    } else {
      alert("Something got wrong " + status);
    }
  });
});

proof of concept fiddle

代码段

var geocoder;
var map;
var geoMarker;

function initialize() {
  var map = new google.maps.Map(
    document.getElementById("map_canvas"), {
      center: new google.maps.LatLng(37.4419, -122.1419),
      zoom: 13,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });
  geoMarker = new google.maps.Marker();
  geoMarker.setPosition(map.getCenter());
  geoMarker.setMap(map);

  $("#location").change(function() {
    var addr = ($('#location').val());

    var geocoder = new google.maps.Geocoder();
    geocoder.geocode({
      'address': addr
    }, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        map.setCenter(results[0].geometry.location);
        geoMarker.setPosition(results[0].geometry.location);
      } else {
        alert("Something got wrong " + status);
      }
    });
  });

}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map_canvas {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js"></script>
<select id="location">
  <option>Dubai</option>
  <option>Sharjah</option>
</select>
<div id="map_canvas"></div>