gpt4 book ai didi

javascript - 使用 json 对象在 map 上添加多个标记

转载 作者:行者123 更新时间:2023-11-30 16:19:49 25 4
gpt4 key购买 nike

我的 index.php 文件如下所示。我想在其中使用 json 对象在其上显示 map 和多个标记。此代码仅适用于一个标记。你能告诉我这段代码如何修改多个标记以及我如何访问 $.ajax() 中的 json 对象吗?

<!DOCTYPE html>
<html>
<head>
<style>
#map { width: 1000px;height: 500px;}
</style>
<script src="https://maps.googleapis.com/maps/api/js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
var latlng = {lat: 31.566470, lng: 74.297723};
var marker;
function initialize() {
var mapCanvas = document.getElementById('map');
var mapOptions = {
center: latlng,
zoom: 11,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(mapCanvas, mapOptions);
marker = new google.maps.Marker({
position: latlng,
title: "Hello World!",
map: map // replaces marker.setMap(map);
});
// now let's set a time interval, let's say every 3 seconds we check the position
setInterval(
function() {
// we make an AJAX call
$.ajax({
dataType: 'JSON', // this means the result (the echo) of the server will be readable as a javascript object
url: 'final.php',
success: function(data) {
// this is the return of the AJAX call. We can use data as a javascript object
console.log(data);
// now we change the position of the marker
marker.setPosition({lat: Number(data.lat), lng: Number(data.lng)});
},
error(error) {
console.log(error);
}

})
}
, 3000
);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map"></div>
</body>
</html>

这是我的final.php

<?php
define('HOST','localhost');
define('USER','root');
define('PASS','1234');
define('DB','coordinates');
$con = mysqli_connect(HOST,USER,PASS,DB);
$arr=[];
for($x=1; $x<=3; $x++){
$query = "SELECT id, longitude, latitude FROM data WHERE bus_id= ".$x." ORDER BY id DESC limit 1" ;
$qry_result = mysqli_query($con,$query);// or die(mysqli_error());
// Insert a new row in the table for each person returned

while($row = mysqli_fetch_array($qry_result)) {
$longitude = $row['longitude'];
$latitude = $row['latitude'];

array_push($arr, [
'lat'=>$longitude,
'lng'=>$latitude,
//'recs'=>$recs
]);
}
}
$record= json_encode($arr);
echo $record;
?>

这是我的json对象

[{"lat":"74.348047","lng":"31.569907"},{"lat":"74.307826","lng":"31.573289"},{"lat":"74.330023","lng":"31.558144"}]

最佳答案

以下内容未经测试,但我认为它应该有效。有一个函数 addmarker,您可以在循环中调用它来处理从 ajax 调用返回的所有数据。如果每隔几秒调用一次,您还需要从 map 中清除旧标记 - 因此使用一个数组来存储对每个新标记的引用。

我在原始代码中发现了与错误处理程序相关的语法错误 - 不确定我是否以正确的方式进行了更正,因为我不使用 jQuery ~ 不过看起来还不错。

<!DOCTYPE html>
<html>
<head>
<style>
#map { width: 1000px;height: 500px;}
</style>
<script src="https://maps.googleapis.com/maps/api/js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
var latlng = { lat: 31.566470, lng: 74.297723 };
var marker;
var map;/* make the map available in all scopes */
var markers=[];/* container to store references to newly added markers */

function addmarker(map, lat, lng, title ){
/* add new marker */
marker = new google.maps.Marker({
position:{ lat:lat,lng:lng },
title:title,
draggable:true,
map:map
});
/*marker.setMap( map );*/
/* store reference */
markers.push( marker );
}


function initialize() {
var mapCanvas = document.getElementById('map');
var mapOptions = {
center: latlng,
zoom: 11,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(mapCanvas, mapOptions);
marker = new google.maps.Marker({
position: latlng,
title: "Hello World!",
map: map // replaces marker.setMap(map);
});




setInterval(
function() {
$.ajax({
dataType: 'JSON',
url: 'ajax.php',
success: function(data) {
/* clear old markers */
markers.forEach( function( e,i,a ){
e.setMap( null );
});

for( var o in data ){
var lat=Number(data[o].lat);
var lng=Number(data[o].lng);
/* Watch the console, see what you get here */

console.log( 'lat:%s, lng:%s',lat,lng );

addmarker.call( this, map, lat, lng, 'Hello World - a title!' );
}
},
error: function( err ){
console.log( err );
}
})
}, 3000 );
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map"></div>
</body>
</html>

我在测试中使用的完整代码

<?php
if( $_SERVER['REQUEST_METHOD']=='POST' ){

$dbhost = 'localhost';
$dbuser = 'root';
$dbpwd = 'xxx';
$dbname = 'xxx';


$conn = new mysqli( $dbhost, $dbuser, $dbpwd, $dbname );

$sql="select
`location_name` as 'title',
`location_map_centre_Latitude` as 'lat',
`location_map_centre_Longitude` as 'lng'
from `maps`
where `countryid`=171
order by rand()
limit 10";


$res=$conn->query( $sql );
if( $res ){

$json=array();
while( $rs=$res->fetch_object() ){
$json[]=array( 'title'=>$rs->title, 'lat'=>$rs->lat, 'lng'=>$rs->lng );
}
header('Content-Type: application/json');
echo json_encode( $json );
}
$conn->close();
exit();
}
?>
<!DOCTYPE html>
<html>
<head>
<style>
#map { width: 1000px;height: 500px;}
</style>
<script src="https://maps.googleapis.com/maps/api/js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>/* initial lat/lng is in Scotland, near Forfar */
var latlng = { lat: 56.61543329027024, lng: -2.9266123065796137 };
var marker;
var map;
var markers=[];/* container to store references to newly added markers */

function addmarker(map, lat, lng, title ){
/* add new marker */
marker = new google.maps.Marker({
position:{ lat:lat,lng:lng },
title:title,
draggable:true,
map:map
});
/* store reference */
markers.push( marker );
}


function initialize() {
var mapCanvas = document.getElementById('map');
var mapOptions = {
center: latlng,
zoom: 9,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(mapCanvas, mapOptions);
marker = new google.maps.Marker({
position: latlng,
title: "Hello World!",
draggable:true,
map: map // replaces marker.setMap(map);
});



/* for testing I only want it to run for a few times */
var i=0;
var m=10;


var igm=setInterval(
function() {
/* testing */
i++;
if( i > m ) clearInterval( igm );
/* testing */


$.ajax({
dataType:'JSON',
method: 'post',
url: document.location.href,
success: function(data) {
/* clear old markers */
markers.forEach( function( e,i,a ){
e.setMap( null );
console.log( 'remove marker:%o', e );
});

for( var o in data ){
var lat=Number(data[o].lat);
var lng=Number(data[o].lng);
var title=data[o].title;

/* Watch the console, see what you get here */
console.log( 'lat:%s, lng:%s',lat,lng );
addmarker.call( this, map, lat, lng, title );
}
},
error: function( err ){
console.warn( 'Error: %s',err );
}
})
}, 5000 );
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map"></div>
</body>
</html>

来自控制台的示例调试信息:

remove marker:Object { __gm={...},  gm_accessors_={...},  position=(54.9094444444, -7.289444444440051),  more...}
remove marker:Object { __gm={...}, gm_accessors_={...}, position=(56.306252, -3.2225129999999353), more...}
remove marker:Object { __gm={...}, gm_accessors_={...}, position=(54.9616666667, -6.9694444444400006), more...}
lat:56.6022222222, lng:-2.63416666667
lat:56.56138345735925, lng:-2.935781240463257
lat:54.5044444444, lng:-7.35222222222

关于javascript - 使用 json 对象在 map 上添加多个标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34918725/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com