Leaflet w/ ajax clustering - javascript

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>

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

retrieve value from mysql database to be used as value in javascript

I am making a map and I want to use the value from the database to be used as the coordinates in the javascript. Please see below:
I want to change the default values of the longitude and latitude by fetching data fro the database but I don't know how.
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>Google Maps</title>
<script src="http://maps.google.com/maps/api/js?sensor=false" t type="text/javascript"></script>
<script type="text/javascript">
function LatiPoint(options)
{
this.UserName = "";
this.JobType = "";
this.UserMood = "";
this.Latitude = "";
this.Longitude = "";
this.Pic = "";
this.Color = "red";
this.OpenInfoWindowInitial = false;
if (options != null)
{
this.UserName = options.UserName;
this.JobType = options.JobType;
this.UserMood = options.UserMood;
this.Latitude = options.Latitude;
this.Longitude = options.Longitude;
this.Pic = options.Pic;
this.Color = ( options.Color == null ? "red" : options.Color );
this.OpenInfoWindowInitial = ( options.OpenInfoWindowInitial == null ? false : options.OpenInfoWindowInitial );
}
}
</script>
<script type="text/javascript">
var LatiPts = new Array();
LatiPts[0] = new LatiPoint({UserName:'Dukot',JobType:'Balulang Cagayan De Oro',UserMood:'drinking beer',Latitude:8.4542363,Longitude:124.63189769999997,Color:'yellow',OpenInfoWindowInitial:true,Pic:''});
LatiPts[1] = new LatiPoint({UserName:'Alot',JobType:'Cagayan De Oro',UserMood:'with classmates',Latitude:8.458353831903118,Longitude:124.63627706511227,Color:'yellow',OpenInfoWindowInitial:true,});
LatiPts[2] = new LatiPoint({UserName:'Lindongan',JobType:'SM Cagayan De Oro',UserMood:'feeling bored',Latitude:8.456188949479728,Longitude:124.62177167875973,Color:'yellow',OpenInfoWindowInitial:true,});
LatiPts[3] = new LatiPoint({UserName:'Galal',JobType:'Carmen Cagayan De Oro',UserMood:'beer',Latitude:8.467607505884205,Longitude:124.62271581633297,Color:'yellow',OpenInfoWindowInitial:true,});
LatiPts[4] = new LatiPoint({UserName:'Belen',JobType:'Cagayan De Oro',UserMood:'beer',Latitude:8.46332028090713,Longitude:124.63537584288326,Color:'yellow',OpenInfoWindowInitial:true,});
</script>
<script type="text/javascript">
//<![CDATA[
var infoWindows = [];
var markers = [];
// A function to create the marker and set up the event window
function createMarker(map, point, title, icon) {
var marker = new google.maps.Marker();
marker.setMap(map);
marker.setPosition(point);
marker.setTitle(title);
marker.setIcon(icon)
google.maps.event.addListener(marker, 'click', function() {
for (var i = 0; i < infoWindows.length; i++)
infoWindows[i].setZIndex(0);
infoWindows[marker.counter].setZIndex(1);
infoWindows[marker.counter].open(marker.getMap(), marker);
});
return marker;
}
function createInfoWindow(html)
{
var infoWindow = new google.maps.InfoWindow();
infoWindow.setContent(html);
infoWindow.setZIndex(0);
return infoWindow;
}
function initialize() {
// Create the Google Map
var map = new google.maps.Map(document.getElementById("map"));
map.setMapTypeId(google.maps.MapTypeId.ROADMAP);
map.setCenter(new google.maps.LatLng(0,0));
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < LatiPts.length; i++) {
var lpt = LatiPts[i];
var point = new google.maps.LatLng(lpt.Latitude, lpt.Longitude);
var html = "<span style='font-family:Arial;font-size:9pt'>";
html += "<span style='font-size:12pt;font-weight:bold'>" + lpt.UserName + "</span><br />";
html += lpt.UserMood.substring(0, 30) + "<br/>";
html += lpt.JobType.substring(0, 30) + "<br/>";
html += "</span>";
var imgPath
if(lpt.Pic != "") {
imgPath = lpt.Pic
} else {
imgPath = "http://maps.gstatic.com/intl/en_ALL/mapfiles/marker.png"
}
//alert("imgPath = " + imgPath + " Pic: " + lpt.Pic)
var icon = new google.maps.MarkerImage(imgPath);
//icon.shadowSize = GSize.ZERO;
var infoWindow = createInfoWindow(html);
infoWindow.open();
var marker = createMarker(map, point, lpt.UserName, icon);
marker.setZIndex(0);
marker.counter = i;
if (LatiPts[i].OpenInfoWindowInitial)
{
infoWindow.open(marker.getMap(), marker);
}
infoWindows.push(infoWindow);
markers.push(marker);
bounds.extend(point);
}
map.setCenter(bounds.getCenter());
map.fitBounds(bounds);
}
function handleNoFlash(code)
{
if ( code == GStreetviewPanorama.ErrorValues.FLASH_UNAVAILABLE )
alert( 'You need flash player to view the panorama.' );
}
function convertLatLngToString(latlng)
{
var hour = parseInt(latlng)
var min = parseInt((latlng - hour) * 60)
var second = (((latlng - hour) * 60) - min) * 60
return (hour + "° " + min + "' " + second.toFixed(2) + "" ");
}
//]]>
</script>
<style type="text/css">
/*give the body height:100% so that its child
elements can have percentage heights*/
body{ margin:0;padding:0;height:100% }
div.fullscreen{
display:block;
position:absolute;
top:0;
left:0;
width:100%;
height:100%;
z-index: 9999;
margin: 0;
padding: 0;
background: inherit;
}
</style>
</head>
<body onload="initialize()">
<div id="map" class="fullscreen" style="width:100%; height:100%"></div>
<div id="streetview" style="width: 650px; height: 400px; display: none;"></div>
<noscript>
<b>JavaScript must be enabled in order for you to use Google Maps.</b>
</noscript>
</body>
</html>
You can do something like this:
<?php /* read from database into variable $results*/ ?>
this.UserName = "<?php echo $results; ?>";
Hope it helps :)

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.

getJSON not working in Safari

Can someone help explain why the following code works in Chrome and IE, but not Safari. I believe the issue is somewhere with the getJSON. It is returning the JSON and works in other browsers, again just not safari. Thanks
Link to actual page: Link to actual page
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="author" content="Lenward Cunningham" />
<meta name="keywords" content="Louisiana Post Game Scores" />
<meta name="description" content="Post Game" />
<meta name="robots" content="all" />
<meta name="copyright" content="Lenward Cunningham" />
<meta name="viewport" content="width=device-width, minimum-scale=1.0, maximum-scale=1.0">
<title>Louisiana Post Game</title>
<link rel="apple-touch-icon" href="img/acadianaPGicon.png">
<link rel="stylesheet" type="text/css" href="assets/_styles.css">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
</head>
<body>
<div id='header'><img src="img/acadianaPG200.jpg"></div>
<div id='content'></div>
<script type="text/javascript">
$(function() {
var url = "https://script.google.com/macros/s/AKfycbwFp0U_pYseCIXVUVfK_wOMoTgno76sk-JXDMGmPResdseOX3Xj/exec";
/*Populate list from JSON */
$.getJSON(url)
.done(function(data) {
for (var d in data) {
/*Process JSON Parameters*/
var game = data[d];
console.log(game)
if (game.matchup) {
var matchUp = game.matchup.split('\n');
var matchUp1 = matchUp[0];
var matchUp2 = matchUp[1];
}
var score1 = '';
var score2 = '';
if (game.score) {
var score = game.score.split('\n');
score1 = score[0];
score2 = score[1];
}
var gameStatus = game.gameStatus;
/*if (game.matchup === null || game.matchup === '')
continue;*/
$('#content').append(
"<div class='game'>"+
"<div class='team'><span class='rank'></span>"+matchUp1+"<span class='score'>"+score1+"</span></div>"+
"<div class='team'><span class='rank'></span>"+matchUp2+"<span class='score'>"+score2+"</span></div>"+
"<div class='status'>"+gameStatus+"</div>"+
"</div>"
);
}
})
});
</script>
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-51502655-1', 'googledrive.com');
ga('send', 'pageview');
</script>
</body>
</html>
Use this json format
$.getJSON(
"https://script.google.com/macros/s/AKfycbwFp0U_pYseCIXVUVfK_wOMoTgno76sk-JXDMGmPResdseOX3Xj/exec",
function (data) {
for (var d in data) {
/*Process JSON Parameters*/
var game = data[d];
console.log(game)
if (game.matchup) {
var matchUp = game.matchup.split('\n');
var matchUp1 = matchUp[0];
var matchUp2 = matchUp[1];
}
var score1 = '';
var score2 = '';
if (game.score) {
var score = game.score.split('\n');
score1 = score[0];
score2 = score[1];
}
var gameStatus = game.gameStatus;
/*if (game.matchup === null || game.matchup === '')
continue;*/
alert();
$('#content').append(
"<div class='game'>" +
"<div class='team'><span class='rank'></span>" + matchUp1 + "<span class='score'>" + score1 + "</span></div>" +
"<div class='team'><span class='rank'></span>" + matchUp2 + "<span class='score'>" + score2 + "</span></div>" +
"<div class='status'>" + gameStatus + "</div>" +
"</div>"
);
}
}
);

Categories

Resources