Place marker on click google maps javascript api

懵懂的女人 提交于 2019-12-30 05:27:08

问题


I have coded a google map in JS Apis.

What I'm trying to achieve is that wherever the user clicks, it places the marker there and outputs its Lat and Lng.

What I have achieved is wherever I click, it outputs the Lat and Lng without dragging the marker there.

Here the Fiddle - http://jsfiddle.net/sarthakbatra1991/87v0obb4/#&togetherjs=3aTj11AiwO

google.maps.event.addListener(map, 'click', function (event) {


        document.getElementById("lat").value = event.latLng.lat();
        document.getElementById("long").value = event.latLng.lng();
        marker.setPosition(lat, lng);
        marker.setMap(map);

    });

Please look at it and help me out here.

Cheers!


回答1:


lat and lng are not defined in the click listener. This should work:

google.maps.event.addListener(map, 'click', function (event) {
  document.getElementById("lat").value = event.latLng.lat();
  document.getElementById("long").value = event.latLng.lng();
  marker.setPosition(event.latLng);
});

updated fiddle

code snippet:

function initialize() {
  var myLatlng = new google.maps.LatLng(40.713956, -74.006653);

  var myOptions = {
    zoom: 8,
    center: myLatlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };
  var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

  var marker = new google.maps.Marker({
    draggable: true,
    position: myLatlng,
    map: map,
    title: "Your location"
  });

  google.maps.event.addListener(marker, 'dragend', function(event) {
    document.getElementById("lat").value = event.latLng.lat();
    document.getElementById("long").value = event.latLng.lng();
  });

  google.maps.event.addListener(map, 'click', function(event) {
    document.getElementById("lat").value = event.latLng.lat();
    document.getElementById("long").value = event.latLng.lng();
    marker.setPosition(event.latLng);
  });
}
google.maps.event.addDomListener(window, "load", initialize());
<style> html,
body,
#map_canvas {
  margin: 0;
  padding: 0;
  height: 100%
}
</style>
<script src="https://maps.googleapis.com/maps/api/js"></script>
Lat:
<input id="lat" name="lat" val="40.713956" />Long:
<input id="long" name="long" val="74.006653" />
<br />
<br />
<div id="map_canvas" style="width: 500px; height: 250px;"></div>


来源:https://stackoverflow.com/questions/35053426/place-marker-on-click-google-maps-javascript-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!