php - 如何使用谷歌地图 api 在网络服务器上绘制多个标记
问题描述
我有以下情况,我想制作一个本地网络服务器,它应该使用谷歌地图 api 在谷歌地图上绘制多个 gps 位置。纬度和经度坐标存储在名为 file.txt 的列表中,例如 lat、long(新行)lat、long ... 并且每分钟添加新坐标。我尝试了各种方法从文件中绘制它们,但我是 html 和 php 的初学者,不知道如何正确地做到这一点。
所以这是用google api绘制标记的代码
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Simple Markers</title>
<style>
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<div id="map"></div>
<script>
function initMap() {
var myLatLng = {lat: -25.363, lng: 131.044};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: myLatLng
});
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: 'Hello World!'
});
}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
</script>
</body>
</html>
基本上在这里我必须从文件中导入位置
var marker = new google.maps.Marker({
position: coordinatesfromfile,
map: map,
title: 'Hello World!'
解决方案
由于这个问题对细节有点轻描淡写,因此以下内容可能不适合您在页面加载时添加标记的初始需求。使用新位置持续更新文本文件过于广泛,无法在这里解决 - 存在几个选项 ~ Ajax 轮询、EventSource / Server Sent Events 或 WebSockets
下面的要点是文本文件由 php 读取,内容的 JSON 表示被创建为 Javascript 变量。然后该initMap
文件遍历这个 javascript 变量 - 尽管我应该强调文本文件的结构不清楚,因此它可能会或可能不会立即工作。对于文本文件中的每一行,在 json 文件中都应该有一个条目 - 该条目包含 lat/lng 坐标。
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Simple Markers</title>
<style>
#map {
height: 100%;
}
html, body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<div id="map"></div>
<script>
<?php
/*
Assuming the file is in the same directory as the page with
the map and that the page is a PHP enabled page.
using `file` will return the contents of a file as an array.
This array is then encoded as a JSON string which we can
process in javascript.
*/
printf("
var locations=%s;",
json_encode( file( 'file.txt', FILE_SKIP_EMPTY_LINES ) )
);
?>
function initMap() {
var myLatLng = {lat: -25.363, lng: 131.044};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: myLatLng
});
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: 'Hello World!'
});
for( var n in locations ){
try{
let line=locations[ n ].split(',');
new google.maps.Marker({
position: { lat:line[0].toFixed(8), lng:line[1].toFixed(8) },
map: map
});
}catch( err ){
console.warn( 'Error: %o Index: %s',err, n )
}
}
}
</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap"></script>
</body>
</html>