问题
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