我正在使用 google maps API 和從 Mysql 資料庫提供的多個設備位置。我可以成功地在地圖上顯示標記并使它們可拖動。如果我將任何標記拖到新位置,它會提示詢問您是否要更新資料庫,如果是,則應該將更新的 lat/lng 發送到資料庫。這不能正常作業,而是總是只更新標記陣列中的最后一項。
請注意,我已使用單個標記成功完成此操作,并且可以在拖動新標記的任何位置對其進行更新。但是對于多個標記,我似乎無法獲取當前拖動標記的 id 和新的緯度/經度資料以發送回 ajax 呼叫以更新該特定標記的資料庫。我想這是因為我沒有訪問當前標記的資料,但我正在努力獲取它。
任何想法我做錯了什么?我知道這一定是我忽略的一些簡單的事情。
這是一個 Fiddle 來演示我的問題:JSFiddle
<!-- php stuff would be up here to get the database and feed the google API. Instead here I've just created the const markers to show the markers. -->
<html>
<head>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAgc6RYO3zsMBE6QVKjkTU-UQ3XhpK0s2A&callback=initMap"></script>
</head>
<body>
<div id="mapCanvas"></div>
</body>
</html>
<style>#mapCanvas {
width: 100%;
height: 850px;
}
</style>
<script>
function initMap() {
var map;
var bounds = new google.maps.LatLngBounds();
var mapOptions = {
mapTypeId: 'hybrid'
};
// Display a map on the web page
map = new google.maps.Map(document.getElementById("mapCanvas"), mapOptions);
map.setTilt(100);
// Multiple markers location, latitude, and longitude
const mapIcon = "https://maps.google.com/mapfiles/marker_grey.png";
const markers = [
['Pike-1', 35.42526738862006, -81.172076628969, mapIcon, 10819],
['Pike-2', 35.425311504805924, -81.17216095766817, mapIcon, 10820],
['Pike-3', 35.425171475622824, -81.17188553479076, mapIcon, 10821],
['Pike-4', 35.42530668524588, -81.17134696588283, mapIcon, 10822],
['Pike-5', 35.42559347700399, -81.17218140606506, mapIcon, 10823],
['Pike-5', 35.426094498781885, -81.17195101338058, mapIcon, 26455],
['Pike-6', 35.42532308059036, -81.17215505637606, mapIcon, 26456]
];
// Place each marker on the map
for (i = 0; i < markers.length; i ) {
var position = new google.maps.LatLng(markers[i][1], markers[i][2]);
var eid = markers[i][4];
bounds.extend(position);
marker = new google.maps.Marker({
position: position,
map: map,
draggable: true,
animation: google.maps.Animation.DROP,
icon: markers[i][3],
equipid: markers[i][4],
title: markers[i][0]
});
//Add listener if marker is moved, then ask to update and call function if yes.
google.maps.event.addListener(marker, 'dragend', function() {
var mytitle = marker.equipid;
var latLng = marker.latLng;
let updateDB = confirm('Update location to database?');
if (updateDB) {
update_marker(latLng, mytitle);
console.log(latLng, mytitle);
}
});
// Center the map to fit all markers on the screen
map.fitBounds(bounds);
function update_marker(Marker, mytitle)
//This is the function that sends the update to the ajax call. Currently not working.
//with multiple markers, I can't get the selected marker equipment ID and new lat/lng.
{
//Update saved marker from DB and map using jQuery Ajax
var mLatLang = marker.getPosition().toUrlValue(); //get marker position - this does not get the marker position, but the last row of the result set from mysql
var mytitle = marker.equipid; //get marker equipment id - this currently gets the last row[id] of the mysql result set.
var myData = {
update: 'true',
name: mytitle,
latlang: mLatLang
};
$.ajax({
type: "POST",
url: "equipment-ajaxupdate-gps.php",
data: myData,
success: function(data) {
alert(data);
console.log(mytitle, mLatLang);
},
error: function(xhr, ajaxOptions, thrownError) {
alert("Error! Update Failed!")
console.log(mytitle, mLatLang);
}
});
}
} //end of for( i = 0)
// Set zoom level
var boundsListener = google.maps.event.addListener((map), 'bounds_changed', function(event) {
this.setZoom(19);
google.maps.event.removeListener(boundsListener);
});
} //End of function(initmap)
// Load initialize function
google.maps.event.addDomListener(window, 'load', initMap);
</script>
uj5u.com熱心網友回復:
我對您的代碼進行了一些更改 - 這似乎作業正常,因為它通過 ajax 呼叫發送正確的詳細資訊,因此從那時起更新資料庫應該是微不足道的。
使用加載 Google Maps api 的腳本標記,您可以指定callback函式,因此無需initMap像使用一樣手動呼叫函式google.maps.event.addDomListener(window, 'load', initMap);
該update_marker函式可以簡化為使用單個引數,該引數是對標記本身的參考。這大大簡化了訪問標記本身的屬性,如下所示self函式中使用的位置(可以是任何名稱 - 它是對標記的參考)
for (i = 0; i < markers.length; i ) {與遍歷陣列元素的笨重回圈相比,更簡單的forEach回圈意味著您不再需要使用name[i][2]型別語法 - 盡管如果實際資料來自您的資料庫,您可能會使用 JSON,這將需要不同的回圈策略.
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' && isset(
$_POST['update'],
$_POST['name'],
$_POST['latlang']
)){
$_POST['date']=date( DATE_RSS );
$payload=json_encode( $_POST );
exit( $payload );
}
?>
<html>
<head>
<style>
#mapCanvas {
width: 100%;
height: 850px;
}
</style>
<script src='//code.jquery.com/jquery-latest.js'></script>
</head>
<body>
<div id="mapCanvas"></div>
<script>
function initMap() {
var map;
var bounds = new google.maps.LatLngBounds();
var mapOptions = {
mapTypeId:'hybrid'
};
map = new google.maps.Map( document.getElementById("mapCanvas"), mapOptions );
map.setTilt(100);
const mapIcon = "https://maps.google.com/mapfiles/marker_grey.png";
const markers = [
['Pike-1', 35.42526738862006, -81.172076628969, mapIcon, 10819],
['Pike-2', 35.425311504805924, -81.17216095766817, mapIcon, 10820],
['Pike-3', 35.425171475622824, -81.17188553479076, mapIcon, 10821],
['Pike-4', 35.42530668524588, -81.17134696588283, mapIcon, 10822],
['Pike-5', 35.42559347700399, -81.17218140606506, mapIcon, 10823],
['Pike-6', 35.426094498781885, -81.17195101338058, mapIcon, 26455],
['Pike-7', 35.42532308059036, -81.17215505637606, mapIcon, 26456]
];
// Place each marker on the map.
// A forEach loop is, IMO, cleaner than the for(i=0;i<n;i ) {} etc
markers.forEach(a=>{
let title=a[0];
let latlng=new google.maps.LatLng( a[1], a[2] );
let icon=a[3];
let eid=a[4];
let marker=new google.maps.Marker({
position: latlng,
map: map,
draggable: true,
animation: google.maps.Animation.DROP,
icon:icon,
/* custom properties */
equipid:eid,
title:title
});
bounds.extend( latlng );
google.maps.event.addListener( marker, 'dragend', function(e) {
if( confirm('Update location to database?') ) {
/*
Within the context of this function `this` refers
to the marker itself that invoked the event handler.
Passing `this` as the function parameter to `update_marker`
allows us to access all properties of the marker from
within that function.
As the marker has been assigned custom properties when it was
added to the map we can access those easily within `update_marker`
*/
update_marker( this );
console.log('Update - Position:%s, Title:%s', this.getPosition().toUrlValue(), this.title );
}
});
function update_marker( self ){
/*
self is the marker reference
*/
$.ajax({
type:"POST",
url:location.href, //"equipment-ajaxupdate-gps.php"
data: {
update:'true',
name:self.title,
latlang:self.getPosition().toUrlValue()
},
success: function( response ) {
console.log( 'Ajax response: %o',response );
bounds.extend( latlng );
map.fitBounds( bounds );
},
error: function( error ) {
alert( "Error! Update Failed!\n" error )
}
});
};
});//end forEach loop
map.fitBounds( bounds );
}
</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=APIKEY&callback=initMap"></script>
</body>
</html>
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/477135.html
標籤:javascript php 谷歌地图 可拖动的
