javascript fetch resulting in undesirable format? - javascript

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);

Related

leaflet live routing using moving marker

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

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>

bootstrap 3 tooltip using html not working

I try to use bootstrap 3 tooltip in my website, and use html to show the content of tooltip, but I get an error: Cannot read property 'user' of undefined.
<div class="container">
Hover over me
Hover over me
Hover over me
Hover over me
Hover over me
</div>
$(document).ready(function() {
var data = [{'user': "Amy"}, {'user': "Betty"}, {'user': "Cindy"}, {'user': "Debby"}, {'user': "Emily"}];
setTooltip(data);
})
function setTooltip(data) {
for (var i = 0; i < data.length; i++) {
$('[data-idx="' + i + '"]').tooltip({
html: true,
title: function() {
return "<p>User: " + data[i].user + "</p>";
}
});
}
}
This is the result in the console:
Does anybody have this problem? Thank you.
You will have to update your setTooltip function:
function setTooltip(data) {
for (var i = 0; i < data.length; i++) {
const name = data[i].user;
$('[data-idx="' + i + '"]').tooltip({
html: true,
title: "<p>User: " + name + "</p>"
});
}
}
Working fiddle:
https://jsfiddle.net/yqdhkcvz/10/
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<link href="https://code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css" rel="stylesheet" type="text/css" />
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script src="https://code.jquery.com/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<title>Tooltip Test</title>
</head>
<body>
<div class="container">
Hover over me
Hover over me
Hover over me
Hover over me
Hover over me
</div>
</body>
</html>
$(document).ready(function() {
var data = [{'user': "Amy"}, {'user': "Betty"}, {'user': "Cindy"}, {'user': "Debby"}, {'user': "Emily"}];
setTooltip(data);
})
function setTooltip(data) {
for (var i = 0; i < data.length; i++) {
$('[data-idx="' + i + '"]').tooltip({
title: "User: " + data[i].user
});
}
}
Please try the above solution it is working fine.
The issue I found in your code that you were using a function() to set the tooltip and the data[i] was undefined within that scope.
Tested link: https://jsbin.com/viyipewale/edit?html,js
Please try this following:
function setTooltip(data) {
for (var i = 0; i < data.length; i++) {
if($('[data-idx="' + i + '"]').length > 0){//Checking the element exists or not
$('[data-idx="' + i + '"]').tooltip({
title: "User: " + data[i].user
});
}
}
}
It's working fine.

Leaflet w/ ajax clustering

i am using leaflet and wanted to add the MarkerCluster plugin.
So far i have a working code that adds markers to a map and adds them to layers.
The following code builds the markers and layers from a database.
<?php include("cliente/config.php");?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr" lang="en-US">
<head profile="http://gmpg.org/xfn/11">
<meta http-equiv="Content-Type" content="text/html; charset="iso-8859-1" />
<title>::: C24 :::</title>
<link rel="stylesheet" href="style2.css" type="text/css" media="screen" />
<link rel="stylesheet" type="text/css" href="hsd-flotr2.css" />
<link rel="stylesheet" href="css/demo.css">
<link rel="stylesheet" href="css/pushy.css">
<script type="text/javascript" src="leaflet/leaflet.js"></script>
<link rel="stylesheet" type="text/css" href="leaflet/leaflet.css" />
<script type="text/javascript" src="leaflet/leaflet.markercluster.js"></script>
<link rel="stylesheet" type="text/css" href="leaflet/MarkerCluster.css" />
<link rel="stylesheet" type="text/css" href="leaflet/MarkerCluster.Default.css" />
<link rel="icon" href="images/favicon.ico" />
<link rel="shortcut icon" href="images/favicon.ico" />
<script type="text/javascript" src="flotr2.min.js"></script>
<script type="text/javascript" src="jquery-3.3.1.min.js"></script>
<script>
function onClick(e) {
alert(this.getLatLng());
}
</script>
</head>
<body>
<?php
$con=mysql_connect($server,$user,$pass) or die(mysql_error());
mysql_select_db($dbname) or die(mysql_error());
$lat = '-39.55660675652325';
$lon = '-72.92878048494458';
$zoom = 7;
$pr = "";
$abc = "";
$abd = "";
$abe = "";
$k = 1;
$v = 'p';
$t = 't';
$w = '_';
$query_11 = mysql_query("SELECT DISTINCT zona FROM alarm;");
while($info_11 = mysql_fetch_array($query_11)) {
$i=1;
$query_1 = mysql_query("SELECT lat, lon FROM alarm WHERE zona = '$info_11[0]' LIMIT 100;");
While($info_1 = mysql_fetch_array($query_1)) {
$abc .= "var ";
$abc .= "$v$k$w$i";
$abc .= "= L.marker([";
$abc .= "$info_1[0],$info_1[1]";
$abc .= "]).on('mouseover', onClick);";
$i++;
}
$abd .= "var t".$k." = L.markerClusterGroup([";
for ($x=1; $x<$i; $x++) {
$abd .= "$v$k$w$x,";
}
$abd .= "]);";
$k++;
}
$l=1;
$abe .= "var overlayMaps = {";
$query_22 = mysql_query("SELECT DISTINCT zona FROM alarm;");
while($info_22 = mysql_fetch_array($query_22)) {
$abe .= "\"$info_22[0]\": t$l,";
$l++;
}
$abe .= "};";
//________________________________________________________________________________________________wie immer ab hier
echo"
<div id='map' style='width: 800px; height: 400px;background:#EEEEEE;'></div>
";
echo"
<script>
function initmap() {
var map;
map = new L.Map('map');
var osmUrl='http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png';
var osmAttrib='';
var osm = new L.TileLayer(osmUrl,{minZoom:4,maxZoom:20,attribution:osmAttrib});
var hull = new L.LatLng('-36.826382900000000','-73.042523000000000');
map.setView(hull,12);
map.addLayer(osm);
$abc
$abd
$abe
L.control.layers(overlayMaps, overlayMaps).addTo(map);
}
initmap();
</script>
";
mysql_close($con);
?>
</body>
</html>
The page on github states that to initiate cluster option you have to add the CSS and JS files witch are on the main page calling tha map via ajax.
The examples i found so far and do not use angular.leaflet state the following use
var markerClusters = L.markerClusterGroup();
for ( var i = 0; i < markers.length; ++i )
{
var m = L.marker([markers[i].lat, markers[i].lng])
.bindPopup( popup );
markerClusters.addLayer( m );
}
map.addLayer(markerClusters);
how can i adapt this.
thanks for helping
Besides loading the Leaflet.markercluster plugin CSS and JS files after Leaflet ones, simply replace your:
L.layerGroup(markersArray)
by:
L.markerClusterGroup().addLayers(markersArray)
Note that there is a slight difference between initialization of Layer Groups, which can directly receive an array of Markers as argument, and MarkerClusterGroup, which must be initialized first, then you can add an array of markers with its addLayers method.
Example:
function abc_fillMarkers() {
for (var zoneK = 0; zoneK < 3; zoneK += 1) {
markersPzoneK_indexI[zoneK] = [];
for (var markerIndexI = 0; markerIndexI < 20; markerIndexI += 1) {
markersPzoneK_indexI[zoneK].push(
L.marker(getRandomLatLng())
);
}
}
}
function abd_fillGroups() {
for (var zoneK = 0; zoneK < 3; zoneK += 1) {
groupsTzoneK[zoneK] = L.markerClusterGroup().addLayers(markersPzoneK_indexI[zoneK]);
}
}
function abe_fillOverlays() {
for (var zoneK = 0; zoneK < 3; zoneK += 1) {
overlayMaps['Group ' + zoneK] = groupsTzoneK[zoneK];
}
}
function initmap() {
var map;
map = new L.Map('map');
var osmUrl = 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png';
var osmAttrib = '© OpenStreetMap contributors';
var osm = new L.TileLayer(osmUrl, {
minZoom: 0,
maxZoom: 20,
attribution: osmAttrib
});
hull = new L.LatLng('-36.826382900000000', '-73.042523000000000');
map.setView(hull, 12);
map.addLayer(osm);
//$abc
abc_fillMarkers();
//$abd
abd_fillGroups();
//$abe
abe_fillOverlays();
L.control.layers(null, overlayMaps, {
collapsed: false
}).addTo(map);
// Add to map all groups initially.
Object.values(overlayMaps).forEach(function(overlay) {
overlay.addTo(map);
});
}
var hull;
var markersPzoneK_indexI = {};
var groupsTzoneK = {};
var overlayMaps = {};
initmap();
function getRandomLatLng() {
return [
hull.lat - 0.05 + 0.1 * Math.random(),
hull.lng - 0.1 + 0.2 * Math.random()
];
}
html,
body,
#map {
margin: 0;
height: 100%;
}
<!-- Leaflet assets -->
<link rel="stylesheet" href="https://unpkg.com/leaflet#1.3.1/dist/leaflet.css" integrity="sha512-Rksm5RenBEKSKFjgI3a41vrjkw4EVPlJ3+OiI65vTjIdo9brlAacEuKOiQ5OFh7cOI1bkDwLqdLw3Zg0cRJAAQ==" crossorigin="" />
<script src="https://unpkg.com/leaflet#1.3.1/dist/leaflet-src.js" integrity="sha512-IkGU/uDhB9u9F8k+2OsA6XXoowIhOuQL1NTgNZHY1nkURnqEGlDZq3GsfmdJdKFe1k1zOc6YU2K7qY+hF9AodA==" crossorigin=""></script>
<!-- Leaflet.markercluster assets -->
<link rel="stylesheet" href="https://unpkg.com/leaflet.markercluster#1.3.0/dist/MarkerCluster.css">
<link rel="stylesheet" href="https://unpkg.com/leaflet.markercluster#1.3.0/dist/MarkerCluster.Default.css">
<script src="https://unpkg.com/leaflet.markercluster#1.3.0/dist/leaflet.markercluster-src.js"></script>
<div id="map"></div>

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