leaflet live routing using moving marker - javascript

Let me first explain what i am trying to do: Every 2 seconds i get array of gps points(lat, long). These points represent a route along which i must move a maker, i'm trying to do it simply by moving a marker from point1 to point2 , then from point2 to point3 and so on. And then when i receive a new array of points i start doing this again.
iam using Leaflet's plugin Leaflet Moving Markers. below is my code from script.js
var latlngs = []
let mapOptions = {
center:[12.8374,77.6443],
zoom:10
}
let map = new L.map('map', mapOptions);
let osm = new L.TileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png').addTo(map);
var marker = {};
var myMovingMarker = {};
var geocodeService = L.esri.Geocoding.geocodeService({
apikey: "my_api_key"
});
function fetch(){
var data = {'email': 'email'};
$.ajax({
url: "url",
type: "POST",
contentType: 'application/x-www-form-urlencoded',
dataType: "JSON",
data: data,
headers: { 'authorization': 'auth_key' },
success: function (resp) {
console.log(resp)
var result = resp;
var output = result['data']['output'];
var singleMobile = resp.data.output[0].mobile
$('#displayHead').append("<tr><th>" + 'vehicle Number' + "</th><th>" + 'mobile' + "</th><th>" + 'ignition' + "</th><th>" + 'last known time' + "</th><th>" + 'track' + "</th><th>" + 'end' + "</th></tr>")
$.each(output, function(index, value) {
var vehicleNo = value.vehicle
var mobile = value.mobile
var ignition = value.ignition
var lastKnownTime = value.last_known_time;
var convertedTime = new Date(lastKnownTime * 1000).toLocaleTimeString("en-US")
var convertedDate = new Date(lastKnownTime * 1000).toLocaleDateString("en-US")
var newTime = (convertedDate + " " +convertedTime)
var lat =value.last_location[1]
var lon =value.last_location[0]
var lastLocation = (lat + " " + lon)
$('#displayArea').append("<tr><td>" + vehicleNo + "</td><td>" + mobile + "</td><td>" + ignition + "</td><td>" + newTime + "<td><button id = 'myBntn' onclick='trackCar("+value.mobile+")'> Track me </button></td>" + "<td><button onclick='stopCar()'> stop tracking </button></td>" + "</td></tr>" );
}); // loop ends here
} // success code ending
}); //ajax code ending
} // function fetch ends here
var autoTrack; // loop/for getting the coordinates of PM contineously
function trackCar(mobile){
autoTrack = setInterval(function(){
var data = {'email': 'email', 'mobile': *mobile*};
$.ajax({
url: "url",
type: "POST",
contentType: 'application/x-www-form-urlencoded',
dataType: "JSON",
data: data,
headers: { 'authorization': 'auth_key' },
success: function (resp) {
console.log(resp)
var lat = parseFloat(resp.data.output.lat).toFixed(4)
var lon = parseFloat(resp.data.output.lng).toFixed(4)
latlngs.push([lat , lon])
geocodeService.reverse().latlng([lat,lon]).run(function (error, result) {
var location = result.address.LongLabel
console.log("output is defined")
console.log(lat + " " + lon);
console.log(latlngs)
}
});
}
// success code ends here
}); // ajax code ends here
}, 2000) //timer ends here
} // function track car ends here
// to stop the looping
function stopCar() {
clearInterval(autoTrack);
};
code from index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="https://unpkg.com/leaflet#1.7.1/dist/leaflet.css" integrity="sha512-xodZBNTC5n17Xt2atTPuE1HxjVMSvLVW9ocqUKLsCC5CXdbqCmblAshOMAS6/keqq/sMZMZ19scR4PsZChSR7A==" crossorigin="" />
<!-- loading css -->
<link rel="stylesheet" href="style.css">
<!-- jquery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
<main class="mainConatiner">
<div class="fetchFromApi">
<button onclick="fetch()">click here</button>
<button id="stop">click me to stop</button>
</div>
<div class="showDetailsInTable">
<table class="fl-table">
<thead id="displayHead"></thead>
<tbody id="displayArea"></tbody>
</table>
</div>
</main>
<div id="map"></div>
<script src="https://unpkg.com/leaflet#1.7.1/dist/leaflet.js" integrity="sha512-XQoYMqMTK8LvdxXYG3nZ448hOEQiglfqkJs1NOQV44cWnUrBc8PkAOcXy20w0vlaXaVUearIOBhiXZ5V3ynxwA==" crossorigin=""></script>
<script src="MovingMarker.js"></script>
<script src="AnimatedMarker.js"></script>
<script src="https://unpkg.com/esri-leaflet#3.0.8/dist/esri-leaflet.js"
integrity="sha512-E0DKVahIg0p1UHR2Kf9NX7x7TUewJb30mxkxEm2qOYTVJObgsAGpEol9F6iK6oefCbkJiA4/i6fnTHzM6H1kEA=="
crossorigin=""></script>
<!-- Load Esri Leaflet Geocoder from CDN -->
<link rel="stylesheet" href="https://unpkg.com/esri-leaflet-geocoder#3.1.3/dist/esri-leaflet-geocoder.css"
integrity="sha512-IM3Hs+feyi40yZhDH6kV8vQMg4Fh20s9OzInIIAc4nx7aMYMfo+IenRUekoYsHZqGkREUgx0VvlEsgm7nCDW9g=="
crossorigin="">
<script src="https://unpkg.com/esri-leaflet-geocoder#3.1.3/dist/esri-leaflet-geocoder.js"
integrity="sha512-mwRt9Y/qhSlNH3VWCNNHrCwquLLU+dTbmMxVud/GcnbXfOKJ35sznUmt3yM39cMlHR2sHbV9ymIpIMDpKg4kKw=="
crossorigin=""></script>
<script src="https://cdn.jsdelivr.net/npm/leaflet-rotatedmarker#0.2.0/leaflet.rotatedMarker.min.js"></script>
<script src="script.js"></script>
</body>
</html>
And finally my problem!!!
What happens each time we receive points:
Marker moves as it is supposed to move(from point1 to point2, from point2 to point3 and so on to the last point.
but when it reaches the last point. for some (unclear to me) reasons moves to the first point again and starts moving from point1 to point2, from point2 to point3 and so on.
Okay, we received points again and our marker again does laps, 3 laps this time.
We received points again, and our marker does 4 laps..
And when we receive points for twentieth time our marker does 20 laps. Why?
Thanks for spending your valuable time on reading this

Related

How do I pass value from REST API to Leaflet Map

Hlo,I am trying to parse the elevation value from REST API to a leaflet map that contains the API with lat, lon. The link to REST API is:-https://developers.airmap.com/docs/elevation-api. I am not able to get the value for elevation for the point location. Anybody please help me to fix it.The code is given as:-
<!DOCTYPE html>
<html>
<head>
<title>Creating mash-ups with Leaflet</title>
<meta charset="utf-8" />
<link rel="stylesheet" href="https://unpkg.com/leaflet#1.7.1/dist/leaflet.css"
integrity="sha512-xodZBNTC5n17Xt2atTPuE1HxjVMSvLVW9ocqUKLsCC5CXdbqCmblAshOMAS6/keqq/sMZMZ19scR4PsZChSR7A=="
crossorigin=""/>
<script src="https://unpkg.com/leaflet#1.7.1/dist/leaflet.js"
integrity="sha512-XQoYMqMTK8LvdxXYG3nZ448hOEQiglfqkJs1NOQV44cWnUrBc8PkAOcXy20w0vlaXaVUearIOBhiXZ5V3ynxwA=="
crossorigin=""></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://auth.airmap.com/js/keycloak.js"></script>
<style>
html, body {
height: 100%;
margin: 0;
}
#map {
width: 1000px;
height: 1000px;
}
</style>
<head>
<body>
<div id="map"></div>
<script >
var map = L.map('map').setView([14.6361111, 42.1608333], 8);
var wmsLayer = L.tileLayer.wms('https://www.gebco.net/data_and_products/gebco_web_services/web_map_service/mapserv?', {
layers: 'GEBCO_LATEST_SUB_ICE_TOPO'
}).addTo(map);
var elevation;
$.getJSON('https://demo.pygeoapi.io/master/collections/ogr_gpkg_poi/items?f=json', function (value) {
var datalayer = L.geoJson(value,{
onEachFeature: function(feature, featureLayer) {
var lat = feature.geometry.coordinates[0];
var lon = feature.geometry.coordinates[1];
var city = feature.properties.name;
$.ajax({
url: 'https://api.airmap.com/elevation/v1/ele/?lat=' + lat + '&lon=' + lon +
'&units=metric& appid=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJjcmVkZW50aWFsX2lkIjoiY3JlZGVudGlhbHxwQUFNWlBxaEx2T2Q2cGZSR2JkMlhDQkdRcTdNIiwiYXBwbGljYXRpb25faWQiOiJhcHBsaWNhdGlvbnx3ZURHZ01oTldtek55c1A4S0xEdlRsQW5QTE0iLCJvcmdhbml6YXRpb25faWQiOiJkZXZlbG9wZXJ8MnpvYmI3eWh4ZVk0cWtDM1BSeDBaSEtNejIzOCIsImlhdCI6MTQ3MTM3OTc0Mn0.MeO0jt6holPt0jdPJvRJrTBi380WsbOPGCEO6u-tfSo',
async: false,
dataType: 'json',
success: function (json) {
elevation = json.data;
}
});
featureLayer.bindPopup("City: " + city + "</br>Elevation: " + elevation + "metres");
}
}).addTo(map);
});
</script>
</body>
</html>
You are almost there. You are using the API in a wrong way. If you read carefully the documetation you will see that the request you are trying to attempt expects ?points=' + lat + ',' + lon + and not ?lat=' + lat + '&lon=' + lon +. Also the same API accepts multiple points at the same time so you don't have to make 10 requests as you are doing right now via a for loop and possibly do only one. Because you are doing them in a synchronous way you will see that the browser is frozen until all of them are resolved. Last but not least , as it was implied in a comment the coordinates you receive is in the form of [lon,lat] and not [lat, lon] so you will need to switch the variables you are storing them
<!DOCTYPE html>
<html>
<head>
<title>Creating mash-ups with Leaflet</title>
<meta charset="utf-8" />
<link rel="stylesheet" href="https://unpkg.com/leaflet#1.7.1/dist/leaflet.css" integrity="sha512-xodZBNTC5n17Xt2atTPuE1HxjVMSvLVW9ocqUKLsCC5CXdbqCmblAshOMAS6/keqq/sMZMZ19scR4PsZChSR7A==" crossorigin="" />
<script src="https://unpkg.com/leaflet#1.7.1/dist/leaflet.js" integrity="sha512-XQoYMqMTK8LvdxXYG3nZ448hOEQiglfqkJs1NOQV44cWnUrBc8PkAOcXy20w0vlaXaVUearIOBhiXZ5V3ynxwA==" crossorigin=""></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://auth.airmap.com/js/keycloak.js"></script>
<style>
html,
body {
height: 100%;
margin: 0;
}
#map {
width: 1000px;
height: 1000px;
}
</style>
<head>
<body>
<div id="map"></div>
<script>
var map = L.map('map').setView([14.6361111, 42.1608333], 8);
var wmsLayer = L.tileLayer.wms('https://www.gebco.net/data_and_products/gebco_web_services/web_map_service/mapserv?', {
layers: 'GEBCO_LATEST_SUB_ICE_TOPO'
}).addTo(map);
var elevation;
$.getJSON('https://demo.pygeoapi.io/master/collections/ogr_gpkg_poi/items?f=json', function(value) {
var datalayer = L.geoJson(value, {
onEachFeature: function(feature, featureLayer) {
var lon = feature.geometry.coordinates[0];
var lat = feature.geometry.coordinates[1];
var city = feature.properties.name;
$.ajax({
url: 'https://api.airmap.com/elevation/v1/ele/?points=' + lat + ',' + lon +
'&units=metric& appid=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJjcmVkZW50aWFsX2lkIjoiY3JlZGVudGlhbHxwQUFNWlBxaEx2T2Q2cGZSR2JkMlhDQkdRcTdNIiwiYXBwbGljYXRpb25faWQiOiJhcHBsaWNhdGlvbnx3ZURHZ01oTldtek55c1A4S0xEdlRsQW5QTE0iLCJvcmdhbml6YXRpb25faWQiOiJkZXZlbG9wZXJ8MnpvYmI3eWh4ZVk0cWtDM1BSeDBaSEtNejIzOCIsImlhdCI6MTQ3MTM3OTc0Mn0.MeO0jt6holPt0jdPJvRJrTBi380WsbOPGCEO6u-tfSo',
async: false,
dataType: 'json',
success: function(json) {
elevation = json.data;
}
});
featureLayer.bindPopup("City: " + city + "</br>Elevation: " + elevation + "metres");
}
}).addTo(map);
});
</script>
</body>
</html>

javascript fetch resulting in undesirable format?

I don't understand what is happening here. I am trying to load data via the code below. when the 3 commented out lines are uncommented the console.log shows the result as[]and the rest of the code does not work even though at this point I am not even using the data that has been fetched.
If I comment out the 3 lines of code and the console.log shows (5) [i, i, i, i, i] and the rest of the code works as desired, which is to plot markers on a leaflet map. I am not sure what this means, and the data inside each set although numbered the same 0-4 seems formatted differently.
Any help would be greatly appreciated.
var groupMarkers = [];
async function getData() {
const response = await fetch('../../Export2.log'); //These are the lines causing problems
var data = await response.text(); //These are the lines causing problems
var formatedData = JSON.parse('[' + data.trim().replace(/\n/g, ',') + ']') //These are the lines causing problems
for (var i = 0; i < 5; i++){
marker = L.marker([51.5, -0.09]).bindPopup("I am a green leaf.");
groupMarkers.push(marker);
}
}
getData();
setInterval(getData, 5000);
L.layerGroup(groupMarkers).addTo(map);
console.log(groupMarkers);
Here is the entire page for testing
<!DOCTYPE html>
<html>
<head>
<title>Map Data Test</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="shortcut icon" type="image/x-icon" href="/favicon.ico" />
<link rel="stylesheet" href="https://unpkg.com/leaflet#1.6.0/dist/leaflet.css" integrity="sha512-xwE/Az9zrjBIphAcBb3F6JVqxf46+CDLwfLMHloNu6KEQCAWi6HcDUbeOfBIptF7tcCzusKFjFw2yuvEpDL9wQ==" crossorigin=""/>
<script src="https://unpkg.com/leaflet#1.6.0/dist/leaflet.js" integrity="sha512-gZwIG9x3wUXg2hdXF6+rVkLF/0Vi9U8D2Ntg4Ga5I5BZpVkVxlJWbSQtXPSiUTtC0TjtGOmxa1AJPuV0CPthew==" crossorigin=""></script>
<style>
html, body {
height: 100%;
margin: 0;
}
#map {
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<div id='map'></div>
<script type="text/javascript">
// Start Map
var map = L.map('map').setView([51.5, -0.09], 7);
L.tileLayer('https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpejY4NXVycTA2emYycXBndHRqcmZ3N3gifQ.rJcFIG214AriISLbB6B5aw', {
maxZoom: 18,
attribution: 'Map data © OpenStreetMap contributors, ' +
'CC-BY-SA, ' +
'Imagery © Mapbox',
id: 'mapbox/light-v9',
tileSize: 512,
zoomOffset: -1
}).addTo(map);
var groupMarkers = [];
async function getData() {
const response = await fetch('../../Export2.log');
var data = await response.text();
var formatedData = JSON.parse('[' + data.trim().replace(/\n/g, ',') + ']')
for (var i = 0; i < 5; i++){
marker = L.marker([51.5, -0.09]).bindPopup("I am a green leaf.");
groupMarkers.push(marker);
}
}
getData();
setInterval(getData, 5000);
L.layerGroup(groupMarkers).addTo(map);
console.log(groupMarkers);
</script>
</body>
</html>
Use a then with fetch:
var groupMarkers = [];
var fg = L.featureGroup().addTo(map);
async function getData() {
const response = fetch("Export.log")
.then(response => response.text()) // or `response.json()` to get a json object
.then(data => {
console.log(data);
fg.clearLayers();
var json = JSON.parse("[" + data.trim().replace(/\n/g, ",") + "]");
console.log(json);
json.forEach((latlng)=>{
console.log(latlng)
var marker = L.marker([latlng.Lat,latlng.Long]).bindPopup("I am a green leaf.");
groupMarkers.push(marker);
fg.addLayer(marker);
});
map.fitBounds(fg.getBounds())
});
}
getData();
setInterval(getData, 5000);

Accessing a variable from js file

Wrote the code for the main site, the geolocation code and the geocoder code.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Electromart</title>
<!-- <link href="//db.onlinewebfonts.com/c/8274996f8cf973b15814827fa281e485?family=TechnojunkW00-Regular" rel="stylesheet" type="text/css"/>-->
<link rel="stylesheet" href="css/eshop.css">
</head>
<body>
<header class="header">
<div class="header__container">
<div class="topheader">
<div class="topheader1">
<?php
?>
</div>
</div>
<div class="header__item">
<div class="logoimage">
<img src="images/logo3.jpg" width="100" height="75" id="idsettingsforlogo" ></img>
</div>
</div>
</div>
<script type="text/javascript" src="js/geoloc.js"></script>
<script type="text/javascript" src="js/geocode.js"></script>
</header>
<footer class="footer">
</footer>
</body>
</html>
geocode.js
var geocoder = new google.maps.Geocoder();
geocoder.geocode({address: lat + ',' + lng}, function (results, status) {
if (status !== google.maps.GeocoderStatus.OK || !results[0]) {
return;
}
var result = results[0];
var city, region, country;
for (var i = 0; i < result.address_components.length; i++) {
if (result.address_components[i].types[0] === "locality") {
city = result.address_components[i];
}
if (result.address_components[i].types[0] === "administrative_area_level_1") {
region = result.address_components[i];
}
if (result.address_components[i].types[0] === "country") {
country = result.address_components[i];
}
}
// alert(city.long_name + ", " + region.long_name + ", " + country.short_name)
console.log(results);
});
Tell me how you can access the city and country variables of the geocode.js file in the main file in the php block. Not sure how to use the Tags (), if you can do without them, write about it.
P.S. In the geocode function, the alert function was used to display the variables, with direct access to the city, country, region variables, and how to display these variables in main.html or main.php - how to access them?
An example you can use Cookie like(example you must edit):
$(document).ready(function () {
createCookie("height", $(window).height(), "10");
});
function createCookie(name, value, days) {
var expires;
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toGMTString();
}
else {
expires = "";
}
document.cookie = escape(name) + "=" + escape(value) + expires + "; path=/";
}
And then read it with PHP:
<?PHP
$_COOKIE["height"];
?>
Else you can use
js can set cookies and reload the page. And php from cookies will take data.
(or can php define geo data, example: https://www.php.net/manual/en/book.geoip.php)

Don't find why my function don't change the temperature degree from Celsius to Fahrenheit

I do a weather app for Free code camp, but i don't know why my button don't change the temperature from celsius to fahrenheit.
I think it's a problem for the recuperation of the variable but i don't know where.
I try some change in my code but i just go around in circles.
This is my javascript :
$(document).ready(function(){
var long;
var lat;
var celsius;
var fahrenheit;
navigator.geolocation.getCurrentPosition(function(position){
long = position.coords.longitude;
lat = position.coords.latitude;
var url = 'http://api.openweathermap.org/data/2.5/weather?lat='+lat+'&lon='+long+'&lang=fr'+'&units=metric&appid=d475e2ed504ab40f4de6c1b3cba9ebcc';
$.getJSON(url, function(data){
var weatherType = data.weather[0].description;
var windSpeed = data.wind.speed;
var icon = data.weather[0].icon;
var city = data.name;
var country = data.sys.country;
var description = data.weather[0].description;
var celsius = data.main.temp;
var fahrenheit = celsius * 9/5 +32;
var Temp = celsius;
$('.card').html( city + '<br> Temp: '+Temp+' °C'+ '<br> Wind Speed:'+windSpeed+'M/s');
$('.icon').html('<img src="http://openweathermap.org/img/w/' + icon + '.png" /> ' + '<br>'+weatherType);
function change() {
if (Temp == 'fahrenheit') {
Temp = 'celsius';
} else if (Temp == 'celsius') {
Temp = 'fahrenheit';
}
$('.btn').on('click', function() { change (); })
console.log(city);
console.log(weatherType);
console.log(windSpeed);
console.log(icon);
};
})
})
});
and the HTML :
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="css/app.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
<title>Weather App</title>
</head>
<body>
<div class="container-fluid">
<div class="row">
<div class='col-sm-6 col-sm-offset-3 col-xs-6 col-xs-offset-3 weather' >
<div class="col-sm-6 text-center card">
</div>
<div class="col-sm-6 text-center text-uppercase icon">
</div>
<button type="button" class="btn degree">°C/°F</button>
</div>
</div>
</div>
<div class="text-center footer">by Mathieu Dupré-Fontana
</div>
<script src="js/app.js"></script>
Can somebody help me please?
Ps: Sorry for my bad English, i'm French .
celsius appears to be a number, not a string, when Temp is set to the value of celisus, Temp is set to a number, not a string
var celsius = data.main.temp;
var fahrenheit = celsius * 9/5 +32;
var Temp = celsius;
Temp would not be equal to "fahrenheit" or "celcius" within change function
function change() {
if (Temp == 'fahrenheit') {
Temp = 'celsius';
} else if (Temp == 'celsius') {
Temp = 'fahrenheit';
}
}
.html() should also be called within change() function, if the expected result is to toggle Celcius and Fahrenheit rendering at HTML on click at element.

Map Marker refresh/Update without refreshing whole map

I cannot figure out how to edit this to make it so the map does not refresh but it continues to refresh the marker to get the updated positions.
the positions are coming from
this line
<?php
$json_pos = file_get_contents("C:\Users\KLAUS\Desktop\New\This SAMP\scriptfiles\positions.json");
?>
right there
<?php
$json_pos = file_get_contents("C:\Users\KLAUS\Desktop\New\This SAMP\scriptfiles\positions.json");
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="refresh" content="1" />
<title>SA:MP live map</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script src="http://maps.google.com/maps/api/js?sensor=false"></script>
<style type="text/css">
#map-canvas { display: inline-block; height: 800px; width: 800px; }
#map-legend { padding: 10px; background-color: rgba(141, 142, 127, 0.46);}
</style>
</head>
<body>
<div id="map-canvas"></div>
<script src="js/SanMap.min.js"></script>
<script type="text/javascript">
var p_pos = <?php echo (empty($json_pos)) ? "" : $json_pos ?>;
var mapType = new SanMapType(0, 1, function (zoom, x, y) {
return x == -1 && y == -1
? "images/tiles/map.outer.png"
: "images/tiles/map." + zoom + "." + x + "." + y + ".png";//Where the tiles are located
});
var satType = new SanMapType(0, 3, function (zoom, x, y) {
return x == -1 && y == -1
? null
: "images/tiles/sat." + zoom + "." + x + "." + y + ".png";//Where the tiles are located
});
var map = SanMap.createMap(document.getElementById('map-canvas'),
{'Map': mapType, 'Satellite': satType}, 2, SanMap.getLatLngFromPos(0,0), false, 'Satellite');
map.controls[google.maps.ControlPosition.TOP_RIGHT].push(document.getElementById('map-legend'));
if(p_pos !== "")
{
for (var i = 0; i < Object.keys(p_pos).length; i++)
{
if(p_pos[i].online == 1) createMarker(i);
}
}
google.maps.event.addListener(map, 'click', function(event) {
var pos = SanMap.getPosFromLatLng(event.latLng);
console.log(pos.x + "," + pos.y);
});
function createMarker(id)
{
var p_windows = new google.maps.InfoWindow({
content: "<p>"+p_pos[id].name+" <b>(ID: "+id+")</b><br>Ping: "+p_pos[id].ping+"</p>"
});
var p_marker = new google.maps.Marker({
position: SanMap.getLatLngFromPos(p_pos[id].x, p_pos[id].y),
map: map,
icon: "images/marker.png"
});
google.maps.event.addListener(p_marker, 'click', function() {
p_windows.open(map,p_marker);
});
}
</script>
</body>
Remove the top header line: <meta http-equiv="refresh" content="1" /> to disable refresh the page. And then add a setInterval function to get the new data from your php service, in the call back --
first use marker.setMap(null) to clear the previous marker and then call your CreateMarker(id).
Or
you can write an updateMarker(id) function, and use marker.setPosition() to update the location.
These are generally idea for you to implement your own code.

Categories

Resources