在我的应用程序中,用户可以使用click
事件找到地点名称,在获取地点名称后,我使用inputField
向用户显示地点名称为此我编写了以下代码。
//辅助函数
function makingGeocodeRequest(obj,callback){
var geocodeInstance=new google.maps.Geocoder();
geocodeInstance.geocode(obj,callback);
}
google.maps.event.addListener(mapInstane,"click",function(event){
makingGeocodeRequest(_.object(["location"],[event.latLng]),
function(res,status){
document.getElementById("field").value=res[0]["formatted_address"];
}
)
})
用户单击保存
按钮后。我根据地点名称查找latlng
值。使用以下代码
makingGeocodeRequest(
_.object(["address"],[document.getElementById("field").value]),
function(res,status){
if (status===google.maps.GeocoderStatus.OK) {
var latLngObj=res[0]["geometry"]["location"];
console.log(latLngObj;
}
}
)
这里的问题是,两个latlng
值不同(点击事件时间latlng值和保存按钮操作latlng值)。
实际上两者都是从 Google
找到的,但它返回不同的 latlng 值。
当单击事件事件时,我正在使用 this 更改光标样式图标。单击保存
按钮后恢复默认光标。
我该如何解决这个问题。有人可以帮助我吗?
谢谢。
最佳答案
要解决您的问题,您可以创建点数组,向该数组添加标记,然后在 map 上渲染该数组的结果。
以下是您可以执行此操作的方法:
使用 JavaScript,
<script type="text/javascript">
var map;
var markersList= [];
function initGMap()
{
var latlng = new google.maps.LatLng(39, 20);
var myOptions = {
zoom: 10,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map"), myOptions);
// add a click event handler to the map object and get the lat Lng and then place it on the map
google.maps.event.addListener(map, "click", function(event)
{
// place a marker
placeMarker(event.latLng);
// display the lat/lng in your form's lat/lng fields
document.getElementById("latVal").value = event.latLng.lat();
document.getElementById("lngVal").value = event.latLng.lng();
});
}
// here is the function to place Marker on the map
function placeMarker(location) {
// first remove all markers if there are any
deleteOverlays();
var marker = new google.maps.Marker({
position: location,
map: map
});
// add marker in markers array
markersList.push(marker);
//map.setCenter(location);
}
// Here you can use this function to delete all markers in the array
function deleteOverlays() {
if (markersList) {
for (i in markersList) {
markersList[i].setMap(null);
}
markersList.length = 0;
}
}
</script>
使用 Html 代码,
<body onload="initGMap()">
<div id="map"></div>
<input type="text" id="latVal">
<input type="text" id="lngVal">
</body>
关于javascript - 如何找到谷歌地图的准确LatLng值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24035842/