如何从Google地图标记获取经度和经度以便在表单中更新?

时间:2017-12-09 12:29:47

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

我想创建一个自动更新标记坐标的表单。 这是我脚本的一部分:

google.maps.event.addListener(map, "click", function(event) {
  marker = new google.maps.Marker({
    position: event.latLng,
    map: map,
  });
  var x = document.getElementById("coordinates");
  if (x.style.display === "none") {
    x.style.display = "block";
  };
  var lati, longi;
  lati = event.latLng;
  longi = event.latLng;
  $("#lat").val(lati);
  $("#lng").val(longi);
});

以下是表格:

<div id="coordinates" class="container" style="margin-top: 10px; display: none;">
  <div class="col-sm-5 col-md-5 col-lg-5">
    <input class="form-control" id="lat" name="lat" placeholder="Latitude" type="text" required>
  </div>
  <div class="col-sm-5 col-md-5 col-lg-5">
    <input class="form-control" id="lng" name="lng" placeholder="Longitude" type="text" required>
  </div>

2 个答案:

答案 0 :(得分:0)

您需要使用.lat()/.lng()分隔它们:

var myLatLng = event.latLng;

var lati = myLatLng.lat();
var lngi = myLatLng.lng();

$("#lat").val(lati);
$("#lng").val(longi);
_^______________________ //Make sure you correct the typo here

答案 1 :(得分:0)

您需要使用.lat()对象的.lng()google.maps.LatLng方法来获取各个字段:

var lati, longi;
lati = event.latLng.lat();
longi = event.latLng.lng();
$("#lat").val(lati);
$("#lng").val(longi);

proof of concept fiddle

screenshot of resulting map

代码段

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
    });
  google.maps.event.addListener(map, "click", function(event) {
    marker = new google.maps.Marker({
      position: event.latLng,
      map: map,
    });
    var x = document.getElementById("coordinates");
    if (x.style.display === "none") {
      x.style.display = "block";
    };

    var lati, longi;
    lati = event.latLng.lat();
    longi = event.latLng.lng();
    $("#lat").val(lati);
    $("#lng").val(longi);

  });
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map_canvas {
  height: 95%;
  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>
<div id="coordinates" class="container" style="margin-top: 10px; display: none;">
  <div class="col-sm-5 col-md-5 col-lg-5">
    <input class="form-control" id="lat" name="lat" placeholder="Latitude" type="text" required>
  </div>
  <div class="col-sm-5 col-md-5 col-lg-5">
    <input class="form-control" id="lng" name="lng" placeholder="Longitude" type="text" required>
  </div>
</div>
<div id="map_canvas"></div>