我现在通过文本框按搜索位置显示Google地图。它工作正常。现在我想要的是将位置图标从地图拖到另一个位置,并借助按钮更新位置。
我正在尝试为此找到函数或API调用,但我仍然在努力使用此代码。
这是我目前的工作代码:
function loadMaps() {
var address = $("#txtAddress").val()
var geo = new google.maps.Geocoder;
geo.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var myLatLngh = results[0].geometry.location;
var myOptions = {
center: myLatLngh,
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU,
position: google.maps.ControlPosition.TOP_CENTER
}
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var marker = new google.maps.Marker({
position: myLatLngh,
title: address
});
marker.setMap(map);
var infowindow = new google.maps.InfoWindow({ content: "<b>Location Address</b><br/> " + address });
infowindow.open(map, marker);
}
else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
答案 0 :(得分:0)
您需要先在标记上启用draggable
选项:
var marker = new google.maps.Marker({
position: myLatLngh,
title: address,
draggable: true
});
然后,您可以在回调中使用marker.getPosition().lat()
和marker.getPosition().lng()
。使用dragend
事件:
marker.addListener('dragend', function() {
// Do something with the positions here
// once the user has finished dragging the marker
console.log(marker.getPosition().lat());
console.log(marker.getPosition().lng());
});