Displaying BBOX hash in URL - javascript

I think I'm doing something wrong in the variables or syntax... i don't know, help me to correct my code. (I'm using Leaflet for the map show)
Desired Behavior
The user should be able to see the BBOX entering the coordinates into the URL, for example:
.com/#013.0,052.0,013.5,052.5
I only care that the BBOX is shown, I don't care that the URL coordinates change when zooming or moving around the map.
My HTML
<!DOCTYPE html>
<html>
<header>
<link rel="stylesheet" href="style.css" />
<link
rel="stylesheet"
href="https://unpkg.com/leaflet#1.9.3/dist/leaflet.css"
integrity="sha256-kLaT2GOSpHechhsozzB+flnD+zUyjE2LlfWPgU04xyI="
crossorigin=""
/>
<script
src="https://unpkg.com/leaflet#1.9.3/dist/leaflet.js"
integrity="sha256-WBkoXOwTeyKclOHuWtc+i2uENFpDZ9YPdf5Hf+D7ewM="
crossorigin=""
></script>
</header>
<body>
<div id="map"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script src="https://unpkg.com/leaflet#1.0.1/dist/leaflet.js"></script>
<script src="leaflet-hash.js"></script>
<script>
var map = L.map("map").setView([42, 12], 4);
// var hash = new L.hash(map);
var urlhash = window.location.hash.substring(1).split("/");
var boundingBox = "";
L.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", {
maxZoom: 22,
minZoom: 1,
continuousWorld: false,
noWrap: false,
attribution:
'Data by OpenStreetMap, under ODbL.',
detectRetina: false,
}).addTo(map);
var bboxField = L.control({
position: "bottomleft",
});
bboxField.onAdd = function (map) {
//create div container for control
var div = L.DomUtil.create("div", "myButtonBar");
//prevent mouse events from propagating through to the map
L.DomEvent.disableClickPropagation(div);
//create custom radio buttons
div.innerHTML =
'BBOX (Left (LON) ,Bottom (LAT), Right (LON), Top (LAT), comma separated, with or without decimal point):<br><input type="text" id="bbox_field"/><button id="setDimensions">Display BBOX</button><button id="remove">Remove</button>';
return div;
};
bboxField.addTo(map);
$(".myButtonBar").css("font-weight", "bold");
if (urlhash[0] !== "") {
$("#bbox_field").val(urlhash[0]);
draw_bbox(urlhash[0]);
}
function draw_bbox(box) {
var myarray = box.split(",");
var bounds = [
[myarray[1], myarray[0]],
[myarray[3], myarray[2]],
];
boundingBox = L.rectangle(bounds, { color: "#ff7800", weight: 1 });
map.removeLayer(boundingBox);
boundingBox.addTo(map);
map.fitBounds(boundingBox.getBounds());
map.setZoom(map.getZoom() - 1);
}
$("#setDimensions").click(function () {
draw_bbox($("#bbox_field").val());
});
$("#bbox_field").keyup(function (event) {
if (event.keyCode === 13) {
$("#setDimensions").click();
}
});
// console.log(bbox)
$("#remove").click(function () {
map.removeLayer(boundingBox);
});
</script>
</body>
</html>
Leaflet Hash Plugin Code
(function(window) {
var HAS_HASHCHANGE = (function() {
var doc_mode = window.documentMode;
return ('onhashchange' in window) &&
(doc_mode === undefined || doc_mode > 7);
})();
L.hash = function(map) {
this.onHashChange = L.Util.bind(this.onHashChange, this);
if (map) {
this.init(map);
}
};
L.hash.parseHash = function(hash) {
if(hash.indexOf('#') === 0) {
hash = hash.substr(1);
}
var args = hash.split("/");
if (args.length == 3) {
var zoom = parseInt(args[0], 10),
lat = parseFloat(args[1]),
lon = parseFloat(args[2]);
if (isNaN(zoom) || isNaN(lat) || isNaN(lon)) {
return false;
} else {
return {
center: new L.LatLng(lat, lon),
zoom: zoom
};
}
} else {
return false;
}
};
L.hash.formatHash = function(map) {
var center = map.getCenter(),
zoom = map.getZoom(),
precision = Math.max(0, Math.ceil(Math.log(zoom) / Math.LN2));
return "#" + [zoom,
center.lat.toFixed(precision),
center.lng.toFixed(precision)
].join("/");
},
L.hash.prototype = {
map: null,
lastHash: null,
parseHash: L.hash.parseHash,
formatHash: L.hash.formatHash,
init: function(map) {
this.map = map;
// reset the hash
this.lastHash = null;
this.onHashChange();
if (!this.isListening) {
this.startListening();
}
},
removeFrom: function(map) {
if (this.changeTimeout) {
clearTimeout(this.changeTimeout);
}
if (this.isListening) {
this.stopListening();
}
this.map = null;
},
onMapMove: function() {
// bail if we're moving the map (updating from a hash),
// or if the map is not yet loaded
if (this.movingMap || !this.map._loaded) {
return false;
}
var hash = this.formatHash(this.map);
if (this.lastHash != hash) {
location.replace(hash);
this.lastHash = hash;
}
},
movingMap: false,
update: function() {
var hash = location.hash;
if (hash === this.lastHash) {
return;
}
var parsed = this.parseHash(hash);
if (parsed) {
this.movingMap = true;
this.map.setView(parsed.center, parsed.zoom);
this.movingMap = false;
} else {
this.onMapMove(this.map);
}
},
// defer hash change updates every 100ms
changeDefer: 100,
changeTimeout: null,
onHashChange: function() {
// throttle calls to update() so that they only happen every
// `changeDefer` ms
if (!this.changeTimeout) {
var that = this;
this.changeTimeout = setTimeout(function() {
that.update();
that.changeTimeout = null;
}, this.changeDefer);
}
},
isListening: false,
hashChangeInterval: null,
startListening: function() {
this.map.on("moveend", this.onMapMove, this);
if (HAS_HASHCHANGE) {
L.DomEvent.addListener(window, "hashchange", this.onHashChange);
} else {
clearInterval(this.hashChangeInterval);
this.hashChangeInterval = setInterval(this.onHashChange, 50);
}
this.isListening = true;
},
stopListening: function() {
this.map.off("moveend", this.onMapMove, this);
if (HAS_HASHCHANGE) {
L.DomEvent.removeListener(window, "hashchange", this.onHashChange);
} else {
clearInterval(this.hashChangeInterval);
}
this.isListening = false;
}
};
L.hash = function(map) {
return new L.hash(map);
};
L.map.prototype.addHash = function() {
this._hash = L.hash(this);
};
L.map.prototype.removeHash = function() {
this._hash.removeFrom();
};
})(window);

Related

Trying to implement own function in an existing GitHub project

L.interpolatePosition = function(p1, p2, duration, t) {
var k = t/duration;
k = (k > 0) ? k : 0;
k = (k > 1) ? 1 : k;
return L.latLng(p1.lat + k * (p2.lat - p1.lat),
p1.lng + k * (p2.lng - p1.lng));
};
L.Marker.MovingMarker = L.Marker.extend({
//state constants
statics: {
notStartedState: 0,
endedState: 1,
pausedState: 2,
runState: 3
},
options: {
autostart: false,
loop: false,
},
initialize: function (latlngs, durations, options) {
L.Marker.prototype.initialize.call(this, latlngs[0], options);
this._latlngs = latlngs.map(function(e, index) {
return L.latLng(e);
});
if (durations instanceof Array) {
this._durations = durations;
} else {
this._durations = this._createDurations(this._latlngs, durations);
}
this._currentDuration = 0;
this._currentIndex = 0;
this._state = L.Marker.MovingMarker.notStartedState;
this._startTime = 0;
this._startTimeStamp = 0; // timestamp given by requestAnimFrame
this._pauseStartTime = 0;
this._animId = 0;
this._animRequested = false;
this._currentLine = [];
this._stations = {};
},
isRunning: function() {
return this._state === L.Marker.MovingMarker.runState;
},
isEnded: function() {
return this._state === L.Marker.MovingMarker.endedState;
},
isStarted: function() {
return this._state !== L.Marker.MovingMarker.notStartedState;
},
isPaused: function() {
return this._state === L.Marker.MovingMarker.pausedState;
},
start: function() {
if (this.isRunning()) {
return;
}
if (this.isPaused()) {
this.resume();
} else {
this._loadLine(0);
this._startAnimation();
this.fire('start');
}
},
resume: function() {
if (! this.isPaused()) {
return;
}
// update the current line
this._currentLine[0] = this.getLatLng();
this._currentDuration -= (this._pauseStartTime - this._startTime);
this._startAnimation();
},
pause: function() {
if (! this.isRunning()) {
return;
}
this._pauseStartTime = Date.now();
this._state = L.Marker.MovingMarker.pausedState;
this._stopAnimation();
this._updatePosition();
},
stop: function(elapsedTime) {
if (this.isEnded()) {
return;
}
this._stopAnimation();
if (typeof(elapsedTime) === 'undefined') {
// user call
elapsedTime = 0;
this._updatePosition();
}
this._state = L.Marker.MovingMarker.endedState;
this.fire('end', {elapsedTime: elapsedTime});
},
addLatLng: function(latlng, duration) {
this._latlngs.push(L.latLng(latlng));
this._durations.push(duration);
},
moveTo: function(latlng, duration) {
this._stopAnimation();
this._latlngs = [this.getLatLng(), L.latLng(latlng)];
this._durations = [duration];
this._state = L.Marker.MovingMarker.notStartedState;
this.start();
this.options.loop = false;
},
addStation: function(pointIndex, duration) {
if (pointIndex > this._latlngs.length - 2 || pointIndex < 1) {
return;
}
this._stations[pointIndex] = duration;
},
onAdd: function (map) {
L.Marker.prototype.onAdd.call(this, map);
if (this.options.autostart && (! this.isStarted())) {
this.start();
return;
}
if (this.isRunning()) {
this._resumeAnimation();
}
},
onRemove: function(map) {
L.Marker.prototype.onRemove.call(this, map);
this._stopAnimation();
},
_createDurations: function (latlngs, duration) {
var lastIndex = latlngs.length - 1;
var distances = [];
var totalDistance = 0;
var distance = 0;
// compute array of distances between points
for (var i = 0; i < lastIndex; i++) {
distance = latlngs[i + 1].distanceTo(latlngs[i]);
distances.push(distance);
totalDistance += distance;
}
var ratioDuration = duration / totalDistance;
var durations = [];
for (i = 0; i < distances.length; i++) {
durations.push(distances[i] * ratioDuration);
}
return durations;
},
_startAnimation: function() {
this._state = L.Marker.MovingMarker.runState;
this._animId = L.Util.requestAnimFrame(function(timestamp) {
this._startTime = Date.now();
this._startTimeStamp = timestamp;
this._animate(timestamp);
}, this, true);
this._animRequested = true;
},
_resumeAnimation: function() {
if (! this._animRequested) {
this._animRequested = true;
this._animId = L.Util.requestAnimFrame(function(timestamp) {
this._animate(timestamp);
}, this, true);
}
},
_stopAnimation: function() {
if (this._animRequested) {
L.Util.cancelAnimFrame(this._animId);
this._animRequested = false;
}
},
_updatePosition: function() {
var elapsedTime = Date.now() - this._startTime;
this._animate(this._startTimeStamp + elapsedTime, true);
},
_loadLine: function(index) {
this._currentIndex = index;
this._currentDuration = this._durations[index];
this._currentLine = this._latlngs.slice(index, index + 2);
},
/**
* Load the line where the marker is
* #param {Number} timestamp
* #return {Number} elapsed time on the current line or null if
* we reached the end or marker is at a station
*/
_updateLine: function(timestamp) {
// time elapsed since the last latlng
var elapsedTime = timestamp - this._startTimeStamp;
// not enough time to update the line
if (elapsedTime <= this._currentDuration) {
return elapsedTime;
}
var lineIndex = this._currentIndex;
var lineDuration = this._currentDuration;
var stationDuration;
while (elapsedTime > lineDuration) {
// substract time of the current line
elapsedTime -= lineDuration;
stationDuration = this._stations[lineIndex + 1];
// test if there is a station at the end of the line
if (stationDuration !== undefined) {
if (elapsedTime < stationDuration) {
this.setLatLng(this._latlngs[lineIndex + 1]);
return null;
}
elapsedTime -= stationDuration;
}
lineIndex++;
// test if we have reached the end of the polyline
if (lineIndex >= this._latlngs.length - 1) {
if (this.options.loop) {
lineIndex = 0;
this.fire('loop', {elapsedTime: elapsedTime});
} else {
// place the marker at the end, else it would be at
// the last position
this.setLatLng(this._latlngs[this._latlngs.length - 1]);
this.stop(elapsedTime);
return null;
}
}
lineDuration = this._durations[lineIndex];
}
this._loadLine(lineIndex);
this._startTimeStamp = timestamp - elapsedTime;
this._startTime = Date.now() - elapsedTime;
return elapsedTime;
},
_animate: function(timestamp, noRequestAnim) {
this._animRequested = false;
// find the next line and compute the new elapsedTime
var elapsedTime = this._updateLine(timestamp);
if (this.isEnded()) {
// no need to animate
return;
}
if (elapsedTime != null) {
// compute the position
var p = L.interpolatePosition(this._currentLine[0],
this._currentLine[1],
this._currentDuration,
elapsedTime);
this.setLatLng(p);
}
if (! noRequestAnim) {
this._animId = L.Util.requestAnimFrame(this._animate, this, false);
this._animRequested = true;
}
}
});
L.Marker.movingMarker = function (latlngs, duration, options) {
return new L.Marker.MovingMarker(latlngs, duration, options);
};
I’m still new with JS and I have this problem. I was working on a js that I got from GitHub
https://github.com/ewoken/Leaflet.MovingMarker. Its a project where you have animated markers moving from a to b. I trying to demonstrate a transport environment for my thesis and I wrote my own functions to it.
function train_station(number){
const countries_train = [];
countries_train[1] = [71, "Germany", "Munich", 48.1351, 11.582, "Train Stration", "Europe"]
countries_train[2] = [72, "England", "London", 51.5074, 0.1278, "Train Stration", "Europe"]
countries_train[3] = [73, "Belgium", "Antwerp", 51.2194, 4.4025, "Train Stration", "Europe"]
countries_train[4] = [74, "France", "Limoges", 45.8336, 1.2611, "Train Stration", "Europe"]
countries_train[5] = [75, "Portugal", "Porto", 41.1579, 8.6291, "Train Stration", "Europe"]
countries_train[6] = [76, "Romania", "Bucharest", 44.4268, 26.1025, "Train Stration", "Europe"]
countries_train[7] = [77, "Italy", "Milan", 45.4642, 9.19, "Train Stration", "Europe"]
return countries_train[number]}
function europe_island(number) {
const countries_island = [];
countries_island[1] = [21, "Iceland", "Reykjavik", 64.1466, 21.9426, "Island", "Europe"]
countries_island[2] = [22, "Ireland", "Dublin", 53.3498, 6.2603, "Island", "Europe"]
return countries_island[number]}
export {europe_core, europe_island, europe_uk, train_station, harbour, europe_scandinavia, international}
Thats my function. I have other function but the structure is the same and the js file I want to implement it in is this:
So, I was trying to implement my function in the script.js file from the GitHub link and every time I import a function of mine the script doesn’t
var map = new L.Map('map', {
zoom: 6,
minZoom: 3,
});
var tileUrl = 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', layer = new L.TileLayer(tileUrl,
{
attribution: 'Maps © OpenStreetMap contributors',
maxZoom: 18
});
map.addLayer(layer);
var parisKievLL = [[48.8567, 2.3508], [50.45, 30.523333]]
var londonParisRomeBerlinBucarest = [[51.507222, -0.1275], [48.8567, 2.3508],
[41.9, 12.5], [52.516667, 13.383333], [44.4166, 26.1]]
var londonBrusselFrankfurtAmsterdamLondon = [[51.507222, -0.1275], [50.85, 4.35],
[50.116667, 8.683333], [52.366667, 4.9], [51.507222, -0.1275]];
var barcelonePerpignanPauBordeauxMarseilleMonaco = [
[41.385064, 2.173403],
[42.698611, 2.895556],
[43.3017, -0.3686],
[44.837912, -0.579541],
[43.296346, 5.369889],
[43.738418, 7.424616]
];
map.fitBounds(londonParisRomeBerlinBucarest);
var marker1 = L.Marker.movingMarker(parisKievLL, [10000]).addTo(map);
L.polyline(parisKievLL).addTo(map);
marker1.once('click', function () {
marker1.start();
marker1.closePopup();
marker1.unbindPopup();
marker1.on('click', function () {
if (marker1.isRunning()) {
marker1.pause();
} else {
marker1.start();
}
});
setTimeout(function () {
marker1.bindPopup('<b>Click me to pause !</b>').openPopup();
}, 2000);
});
marker1.bindPopup('<b>Click me to start !</b>', {closeOnClick: false});
marker1.openPopup();
var marker2 = L.Marker.movingMarker(londonParisRomeBerlinBucarest, [3000, 9000, 9000, 4000], {autostart: true}).addTo(map);
L.polyline(londonParisRomeBerlinBucarest, {color: 'red'}).addTo(map);
marker2.on('end', function () {
marker2.bindPopup(message(), {closeOnClick: false})
.openPopup();
});
var marker3 = L.Marker.movingMarker(londonBrusselFrankfurtAmsterdamLondon,
[2000, 2000, 2000, 2000], {autostart: true, loop: true}).addTo(map);
marker3.loops = 0;
marker3.bindPopup('', {closeOnClick: false});
var marker4 = L.Marker.movingMarker([[45.816667, 15.983333]], []).addTo(map);
marker3.on('loop', function (e) {
marker3.loops++;
if (e.elapsedTime < 50) {
marker3.getPopup().setContent("<b>Loop: " + marker3.loops + "</b>")
marker3.openPopup();
setTimeout(function () {
marker3.closePopup();
if (!marker1.isEnded()) {
marker1.openPopup();
} else {
if (marker4.getLatLng().equals([45.816667, 15.983333])) {
marker4.bindPopup('Click on the map to move me !');
marker4.openPopup();
}
}
}, 2000);
}
});
map.on("click", function (e) {
marker4.moveTo(e.latlng, 2000);
});
var marker5 = L.Marker.movingMarker(barcelonePerpignanPauBordeauxMarseilleMonaco, 10000, {autostart: true}).addTo(map);
marker5.addStation(1, 2000);
marker5.addStation(2, 2000);
marker5.addStation(3, 2000);
marker5.addStation(4, 2000);
L.polyline(barcelonePerpignanPauBordeauxMarseilleMonaco,
{color: 'green'}).addTo(map);
<!DOCTYPE html>
<html>
<head>
<title> Leaflet.MovingMarker Demo Page </title>
<meta charset="UTF-8">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="description" content="Leaflet plugin to animate marker !">
<meta name="keywords" content="Leaflet MovingMarker marker ewoken github animation">
<meta name="author" content="Ewoken">
<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.css"/>
<link rel="stylesheet" href="style.css"/>
</head>
<body>
<main>
<h1> Demo of Leaflet.MovingMarker </h1>
<section>
<div id="map">
</div>
</section>
</main>
<script type="text/javascript" src="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.js"></script>
<script type="text/javascript" src="MovingMarker.js"></script>
<script type="text/javascript" src="script.js">
</script>
</body>
</html>
work anymore.
It shows that "referenceerror L is not defined" and if I do the "Import * as L from 'leaflet'" is says that "referenceerror: window is not defined"
I havent changed the code, it’s just the imports. As soon as I type import the variables in the script turn from purple to grey and dont work anymore.
Im using IntelliJ 2021 IDE Ultimate 2021
I have the type:module in my dependencies so the Imports and exports work.
I change it module on the html file as well
I deleted the folder and reinstalled everything again
Thanks for your time and help guys.

How to update the markers in real-time using ajax

May I know how do I update the location in real-time, if the location value has been changed. The current code is what I used to retrieve the data from the database. I tried many solutions such as set interval or timeout but that did not help me in solving the problem.
$.ajax({
type: "GET",
url: ')',
success: function (data, status, xhr) {
for (var i = 0; i < data.Table.length; i++) {
if (createdA === false) {
for (var a = 0; a <= 200; a++) {
a1 = data.Table[i].Latitude;
a2 = data.Table[i].Longitude;
a5 = data.Table[i].DeviceImei;
}
createMarkerA([a1, a2]);
shownA = true;
createdA = true;
setInterval(groupOne(), 10000);
}
else if (shownA === false) {
for (var a3 = 0; a3 < 200; a3++) {
showMarker(markersA[a3]);
shownA = true;
}
}
else if (shownA === true) {
for (var a4 = 0; a4 < 200; a4++) {
hideMarker(markersA[a4]);
shownA = false;
}
}
}
},
error: function (xhr) {
alert(xhr.responseText);
}
});
//This is the code to initialize the map
//centers the map at using the 2 points as reference
var center = L.bounds([, ], [, ]).getCenter();
//it sets the map to the pre-defined div container
var map = L.map('test_map').setView([center.x, center.y], 12);
var basemap = L.tileLayer('https://maps-{s}.onemap.sg/v3/Original/{z}/{x}/{y}.png', {
detectRetina: true,
maxZoom: 20,
minZoom: 11
});
basemap.addTo(map);
var markersLayer = new L.LayerGroup(); //layer contain searched elements
map.addLayer(markersLayer);
var controlSearch = new L.Control.Search({
position: 'topright',
layer: markersLayer,
initial: false,
zoom: 18,
marker: false
})
map.addControl(controlSearch);
L.circle([, ], 50, { color: '#DA2E2E', opacity: 2, fillColor: 'blue', fillOpacity: .3 }).bindPopup('').addTo(map);
L.circle([, ], 50, { color: '#DA2E2E', opacity: 2, fillColor: 'blue', fillOpacity: .3 }).bindPopup('').addTo(map);
// The code to initialize the markers
var markers = [];
function pushMarker(marker) {
markers.push(marker);
}
function createMarker(data) {
var marker = new L.marker([data[0], data[1]]);
pushMarker(marker);
showMarker(marker);
}
//General Functions
function hideMarker(marker) {
map.removeLayer(marker);
}
function showMarker(marker) {
map.addLayer(marker);
}
var createdA = false;
var shownA = false;
var markersA = [];
var a1;
var a2;
var a5;
function createMarkerA(data) {
$.ajax({
type: "GET",
url: '',
success: function (data, status, xhr) {
for (var i = 0; i < 4; i++) {
var customPopup = 'Coordinates X: ' + data.Table[i].Latitude + '</br>Coordinates Z: ' + data.Table[i].Longitude + '</br>Station: ' + data.Table[i].Station + ' </br> Box: ' + data.Table[i].Box + '</br > Timestamp: ' + data.Table[i].LocationSend;
var customOptions =
{
'maxWidth': '500',
'className': 'custom'
};
var marker = L.marker(new L.LatLng(data.Table[i].Latitude, data.Table[i].Longitude, data.Table[i].Station));
marker.bindPopup(customPopup, customOptions);
pushMarker(marker);
showMarker(marker);
}
},
error: function (xhr) {
alert(xhr.responseText);
}
});
}
function groupOne() {
$.ajax({
type: "GET",
url: '',
success: function (data, status, xhr) {
for (var i = 0; i < 4; i++) {
if (createdA === false) {
for (var a = 0; a < 200; a++) {
a1 = data.Table[i].Latitude;
a2 = data.Table[i].Longitude;
}
createMarkerA([a1, a2]);
shownA = true;
createdA = true;
}
else if (shownA === false) {
for (var a3 = 0; a3 <= 4; a3++) {
showMarker(markersA[a3]);
shownA = true;
}
}
else if (shownA === true) {
for (var a4 = 0; a4 <= 4; a4++) {
hideMarker(markersA[a4]);
shownA = false;
}
}
}
},
error: function (xhr) {
alert(xhr.responseText);
}
});
Just I am taking some static points to change the point without refresh the page
<html>
<head>
<title>Leaflet geolocate example</title>
<link rel="stylesheet" href="https://npmcdn.com/leaflet#0.7.7/dist/leaflet.css" />
<script src="https://npmcdn.com/leaflet#0.7.7/dist/leaflet.js"></script>
<script language="javascript">
var map;
var markers = [];
var center = L.bounds([40.712, -74.227], [40.774, -74.125]).getCenter();
//alert(center.x);
function init() {
map = new L.Map('map');
L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap contributors',
maxZoom: 18
}).addTo(map);
map.attributionControl.setPrefix(''); // Don't show the 'Powered by Leaflet' text.
var seconds = 0.005;
map.setView(new L.LatLng(center.x, center.y), 12);
setmarkers(seconds);
var myTimer = setInterval(function () {
center.x = center.x + seconds + 0.01;
center.y = center.y + seconds + 0.01;
getmarkers(seconds);
seconds = seconds + 0.01;
}, 2000);
}
function getmarkers(v) {
//alert(v);
for (var i = 0; i < 10; i++) {
var location = new L.LatLng(center.x + i * v, center.y + i * v);
markers[i].setLatLng(location);
markers[i].addTo(map);
}
}
function setmarkers(v) {
alert(v);
var radius = 30;
for (var i = 0; i < 10; i++) {
var location = new L.LatLng(center.x + i * v, center.y + i * v)
var mark = L.marker(location);
markers.push(mark);
}
}
function onLocationFound(e) {
var radius = e.accuracy / 2;
radius = 30;
var location = e.latlng
L.marker(location).addTo(map)
L.circle(location, radius).addTo(map);
alert(location.lat);
alert(location.lng);
addinlocations(location);
}
function onLocationError(e) {
alert(e.message);
}
function getLocationLeaflet() {
map.on('locationfound', onLocationFound);
map.on('locationerror', onLocationError);
map.locate({ setView: true, maxZoom: 16 });
}
function pushMarker(marker) {
markers.push(marker);
}
function addinlocations(pot) {
for (var i = 0; i < 10; i++) {
var nmarker = new L.LatLng(pot.lat + i * 0.5, pot.lng * 0.5);
var radius = 20;
var location = nmarker
L.marker(location).addTo(map)
L.circle(location, radius).addTo(map);
// pushMarker(nmarker);
}
}
</script>
</head>
<body onLoad="javascript:init();">
<div id="map" style="height: 500px"></div>
<input type="button" value="Locate me!" onClick="javascript:getLocationLeaflet();">
</body>
</html>
<html>
<head>
<title>Leaflet geolocate example</title>
<link rel="stylesheet" href="https://npmcdn.com/leaflet#0.7.7/dist/leaflet.css" />
<script src="https://npmcdn.com/leaflet#0.7.7/dist/leaflet.js"></script>
<script language="javascript">
var map;
var markers = [];
var createdA = false;
var shownA = false;
var markersA = [];
var markersA = [];
var a1;
var a2;
var a5;
var center = L.bounds([39.61, -105.02], [39.77, -105.23]).getCenter();
function init() {
map = new L.Map('test_map').setView(new L.LatLng(center.x, center.y), 12);;
var basemap = L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap contributors',
detectRetina: true,
maxZoom: 20,
minZoom: 9
});
basemap.addTo(map);
var data = [];
var d1 = { Table: { Latitude: 39.61, Longitude: -105.02, Station: 'This is Littleton, CO.', Box: 'Box', LocationSend: 'testing1' } };
var d2 = { Table: { Latitude: 39.74, Longitude: -104.99, Station: 'This is Denver, CO.', Box: 'Box', LocationSend: 'testing2' } };
var d3 = { Table: { Latitude: 39.73, Longitude: -104.8, Station: 'This is Aurora, CO.', Box: 'Box', LocationSend: 'testing3' } };
var d4 = { Table: { Latitude: 39.733, Longitude: -104.821, Station: 'This is Littleton, CO.', Box: 'Box', LocationSend: 'testing4' } };
var d5 = { Table: { Latitude: 39.742, Longitude: -105.002, Station: 'This is Denver, CO.', Box: 'Box', LocationSend: 'testing5' } };
var d6 = { Table: { Latitude: 39.734, Longitude: -104.811, Station: 'This is Aurora, CO.', Box: 'Box', LocationSend: 'testing6' } };
data.push(d1);
data.push(d2);
data.push(d3);
data.push(d4);
data.push(d5);
data.push(d6);
markersA.push(L.marker(new L.LatLng(39.61, -105.02)));
markersA.push(L.marker(new L.LatLng(39.74, -104.99)));
markersA.push(L.marker(new L.LatLng(39.73, -104.8)));
map.addLayer(markersA[0]);
map.addLayer(markersA[1]);
map.addLayer(markersA[2]);
var myTimer = setInterval(function () {
groupOne(data);
}, 2000);
var markersLayer = L.layerGroup(markersA);
map.addLayer(markersLayer);
var controlSearch = new L.Control.Search({
position: 'topright',
layer: markersLayer,
initial: false,
zoom: 15,
marker: false
})
map.addControl(controlSearch);
}
function pushMarker(marker) {
markers.push(marker);
}
function createMarker(data) {
var marker = new L.marker([data[0], data[1]]);
pushMarker(marker);
}
function showMarker(marker) {
map.addLayer(marker);
}
function hideMarker(marker, i) {
var locate = marker.getLatLng();
markersA[i].setLatLng(locate);
}
function createMarkerA(data) {
var valid = true;
for (var i = 0; i < data.length; i++) {
var customPopup = 'Coordinates X: ' + data[i].Table.Latitude + '</br>Coordinates Z: ' + data[i].Table.Longitude + '</br>Station: ' + data[i].Table.Station + ' </br> Box: ' + data[i].Table.Box + '</br > Timestamp: ' + data[i].Table.LocationSend;
//var customOptions =
// {
// 'maxWidth': '500',
// 'className': 'custom'
// };
//var marker = L.marker(new L.LatLng(data[i].Table.Latitude, data[i].Table.Longitude, data[i].Table.Station));
var marker = L.marker(new L.LatLng(data[i].Table.Latitude, data[i].Table.Longitude));
marker.bindPopup(customPopup);
pushMarker(marker);
}
}
function groupOne(data) {
//$.ajax({
// type: "GET",
// url: '',
// data:data,
// success: function (data, status, xhr) {
if (createdA == false) {
createMarkerA(data);
shownA = true;
createdA = true;
}
else if (shownA == false) {
for (var a = 0; a <= 2; a++) {
hideMarker(markers[a],a);
}
shownA = true;
}
else if (shownA == true) {
for (var aa = 3;aa<=5;aa++) {
var i = aa - 3;
hideMarker(markers[aa], i);
}
shownA = false;
}
//}
//,
//error: function (xhr) {
// alert(xhr.responseText);
//}
//});
}
</script>
</head>
<body onLoad="javascript:init();">
<div id="test_map" style="height: 500px"></div>
</body>
</html>
<html>
<head>
<title>Leaflet geolocate example</title>
<link rel="stylesheet" href="https://unpkg.com/leaflet#1.3.0/dist/leaflet.css" />
<link rel="stylesheet" href="styles.css">
<script language="javascript">
var markers = [];
var createdA = false;
var shownA = false;
var markersA = [];
var markersA = [];
var a1;
var a2;
var a5;
var data1 = [];
var center = L.bounds([1.56073, 104.11475], [1.16, 103.502]).getCenter();
function init() {
map = new L.Map('test_map').setView(new L.LatLng(center.x, center.y), 12);;
var basemap = L.tileLayer('https://maps-
{s}.onemap.sg/v3/Original/{z}/{x}/{y}.png', {
attribution: '<img src="https://docs.onemap.sg/maps/images/oneMap64-
01.png" style="height:20px;width:20px;"/> New OneMap | Map data © contributors,
Singapore Land Authority',
detectRetina: true,
maxZoom: 20,
minZoom: 9
});
basemap.addTo(map);
$.ajax({
type: "GET",
url: '',
success: function (data, status, xhr) {
for (var i = 0; i < data.Table.length; i++) {
for (var s = 1; s < data.Table.length; s++) {
var d1 = { Table: { Latitude: data.Table[i].Latitude,
Longitude: data.Table[i].Longitude, Station: 'This is Littleton, CO.', Box:
'Box', LocationSend: 'testing1' } };
var d2 = { Table: { Latitude: data.Table[s].Latitude,
Longitude: data.Table[s].Longitude, Station: 'This is Denver, CO.', Box: 'Box',
LocationSend: 'testing2' } };
data1.push(d1);
data1.push(d2);
markersA.push(L.marker(new L.LatLng(data.Table[i].Latitude,
data.Table[i].Longitude)));
markersA.push(L.marker(new L.LatLng(data.Table[s].Latitude,
data.Table[s].Longitude)));
map.addLayer(markersA[0]);
map.addLayer(markersA[1]);
}
}
},
error: function (xhr) {
alert(xhr.responseText);
}
});
var myTimer = setInterval(function () {
groupOne(data1);
}, 2000);
}
function pushMarker(marker) {
markers.push(marker);
}
function createMarker(data1) {
var marker = new L.marker([data1[0], data1[1]]);
pushMarker(marker);
}
function showMarker(marker) {
map.addLayer(marker);
}
function hideMarker(marker, i) {
var locate = marker.getLatLng();
markersA[i].setLatLng(locate);
}
function createMarkerA(data1) {
var valid = true;
for (var i = 0; i < data1.length; i++) {
var customPopup = 'Coordinates X: ' + data1[i].Table.Latitude +
'</br>Coordinates Z: ' + data1[i].Table.Longitude + '</br>Station: ' +
data1[i].Table.Station + ' </br> Box: ' + data1[i].Table.Box + '</br >
Timestamp: ' + data1[i].Table.LocationSend;
//var customOptions =
// {
// 'maxWidth': '500',
// 'className': 'custom'
// };
//var marker = L.marker(new L.LatLng(data[i].Table.Latitude,
data[i].Table.Longitude, data[i].Table.Station));
var marker = L.marker(new L.LatLng(data1[i].Table.Latitude,
data1[i].Table.Longitude));
marker.bindPopup(customPopup);
pushMarker(marker);
}
}
function groupOne(data) {
//$.ajax({
// type: "GET",
// url: '',
// data:data,
// success: function (data, status, xhr) {
if (createdA == false) {
createMarkerA(data);
shownA = true;
createdA = true;
}
else if (shownA == false) {
for (var a = 0; a <= 2; a++) {
hideMarker(markers[a], a);
}
shownA = true;
}
else if (shownA == true) {
for (var aa = 3; aa <= 5; aa++) {
var i = aa - 3;
hideMarker(markers[aa], i);
}
shownA = false;
}
//}
//,
//error: function (xhr) {
// alert(xhr.responseText);
//}
//});
}
</script>
</head>
<body onLoad="javascript:init();">
<div id='test_map' style=" height: 800px; "></div>

How to use the points which come from the leaflet file layer plugin?

/*
* Load files *locally* (GeoJSON, KML, GPX) into the map
* using the HTML5 File API.
*
* Requires Mapbox's togeojson.js to be in global scope
* https://github.com/mapbox/togeojson
*/
(function (factory, window) {
// define an AMD module that relies on 'leaflet'
if (typeof define === 'function' && define.amd && window.toGeoJSON) {
define(['leaflet'], function (L) {
factory(L, window.toGeoJSON);
});
} else if (typeof module === 'object' && module.exports) {
// require('LIBRARY') returns a factory that requires window to
// build a LIBRARY instance, we normalize how we use modules
// that require this pattern but the window provided is a noop
// if it's defined
module.exports = function (root, L, toGeoJSON) {
if (L === undefined) {
if (typeof window !== 'undefined') {
L = require('leaflet');
} else {
L = require('leaflet')(root);
}
}
if (toGeoJSON === undefined) {
if (typeof window !== 'undefined') {
toGeoJSON = require('togeojson');
} else {
toGeoJSON = require('togeojson')(root);
}
}
factory(L, toGeoJSON);
return L;
};
} else if (typeof window !== 'undefined' && window.L && window.toGeoJSON) {
factory(window.L, window.toGeoJSON);
}
}(function fileLoaderFactory(L, toGeoJSON) {
var FileLoader = L.Class.extend({
includes: L.Mixin.Events,
options: {
layer: L.geoJson,
layerOptions: {},
fileSizeLimit: 1024
},
initialize: function (map, options) {
this._map = map;
L.Util.setOptions(this, options);
this._parsers = {
geojson: this._loadGeoJSON,
json: this._loadGeoJSON,
gpx: this._convertToGeoJSON,
kml: this._convertToGeoJSON
};
},
load: function (file, ext) {
var parser,
reader;
// Check file is defined
if (this._isParameterMissing(file, 'file')) {
return false;
}
// Check file size
if (!this._isFileSizeOk(file.size)) {
return false;
}
// Get parser for this data type
parser = this._getParser(file.name, ext);
if (!parser) {
return false;
}
// Read selected file using HTML5 File API
reader = new FileReader();
reader.onload = L.Util.bind(function (e) {
var layer;
try {
this.fire('data:loading', { filename: file.name, format: parser.ext });
layer = parser.processor.call(this, e.target.result, parser.ext);
this.fire('data:loaded', {
layer: layer,
filename: file.name,
format: parser.ext
});
} catch (err) {
this.fire('data:error', { error: err });
}
}, this);
// Testing trick: tests don't pass a real file,
// but an object with file.testing set to true.
// This object cannot be read by reader, just skip it.
if (!file.testing) {
reader.readAsText(file);
}
// We return this to ease testing
return reader;
},
loadMultiple: function (files, ext) {
var readers = [];
if (files[0]) {
files = Array.prototype.slice.apply(files);
while (files.length > 0) {
readers.push(this.load(files.shift(), ext));
}
}
// return first reader (or false if no file),
// which is also used for subsequent loadings
return readers;
},
loadData: function (data, name, ext) {
var parser;
var layer;
// Check required parameters
if ((this._isParameterMissing(data, 'data'))
|| (this._isParameterMissing(name, 'name'))) {
return;
}
// Check file size
if (!this._isFileSizeOk(data.length)) {
return;
}
// Get parser for this data type
parser = this._getParser(name, ext);
if (!parser) {
return;
}
// Process data
try {
this.fire('data:loading', { filename: name, format: parser.ext });
layer = parser.processor.call(this, data, parser.ext);
this.fire('data:loaded', {
layer: layer,
filename: name,
format: parser.ext
});
} catch (err) {
this.fire('data:error', { error: err });
}
},
_isParameterMissing: function (v, vname) {
if (typeof v === 'undefined') {
this.fire('data:error', {
error: new Error('Missing parameter: ' + vname)
});
return true;
}
return false;
},
_getParser: function (name, ext) {
var parser;
ext = ext || name.split('.').pop();
parser = this._parsers[ext];
if (!parser) {
this.fire('data:error', {
error: new Error('Unsupported file type (' + ext + ')')
});
return undefined;
}
return {
processor: parser,
ext: ext
};
},
_isFileSizeOk: function (size) {
var fileSize = (size / 1024).toFixed(4);
if (fileSize > this.options.fileSizeLimit) {
this.fire('data:error', {
error: new Error(
'File size exceeds limit (' +
fileSize + ' > ' +
this.options.fileSizeLimit + 'kb)'
)
});
return false;
}
return true;
},
_loadGeoJSON: function _loadGeoJSON(content) {
var layer;
if (typeof content === 'string') {
content = JSON.parse(content);
}
layer = this.options.layer(content, this.options.layerOptions);
if (layer.getLayers().length === 0) {
throw new Error('GeoJSON has no valid layers.');
}
if (this.options.addToMap) {
layer.addTo(this._map);
}
return layer;
},
_convertToGeoJSON: function _convertToGeoJSON(content, format) {
var geojson;
// Format is either 'gpx' or 'kml'
if (typeof content === 'string') {
content = (new window.DOMParser()).parseFromString(content, 'text/xml');
}
geojson = toGeoJSON[format](content);
return this._loadGeoJSON(geojson);
}
});
var FileLayerLoad = L.Control.extend({
statics: {
TITLE: 'Load local file (GPX, KML, GeoJSON)',
LABEL: '⌅'
},
options: {
position: 'topleft',
fitBounds: true,
layerOptions: {},
addToMap: true,
fileSizeLimit: 1024
},
initialize: function (options) {
L.Util.setOptions(this, options);
this.loader = null;
},
onAdd: function (map) {
this.loader = L.Util.fileLoader(map, this.options);
this.loader.on('data:loaded', function (e) {
// Fit bounds after loading
if (this.options.fitBounds) {
window.setTimeout(function () {
map.fitBounds(e.layer.getBounds());
}, 500);
}
}, this);
// Initialize Drag-and-drop
this._initDragAndDrop(map);
// Initialize map control
return this._initContainer();
},
_initDragAndDrop: function (map) {
var callbackName;
var thisLoader = this.loader;
var dropbox = map._container;
var callbacks = {
dragenter: function () {
map.scrollWheelZoom.disable();
},
dragleave: function () {
map.scrollWheelZoom.enable();
},
dragover: function (e) {
e.stopPropagation();
e.preventDefault();
},
drop: function (e) {
e.stopPropagation();
e.preventDefault();
thisLoader.loadMultiple(e.dataTransfer.files);
map.scrollWheelZoom.enable();
}
};
for (callbackName in callbacks) {
if (callbacks.hasOwnProperty(callbackName)) {
dropbox.addEventListener(callbackName, callbacks[callbackName], false);
}
}
},
_initContainer: function () {
var thisLoader = this.loader;
// Create a button, and bind click on hidden file input
var fileInput;
var zoomName = 'leaflet-control-filelayer leaflet-control-zoom';
var barName = 'leaflet-bar';
var partName = barName + '-part';
var container = L.DomUtil.create('div', zoomName + ' ' + barName);
var link = L.DomUtil.create('a', zoomName + '-in ' + partName, container);
link.innerHTML = L.Control.FileLayerLoad.LABEL;
link.href = '#';
link.title = L.Control.FileLayerLoad.TITLE;
// Create an invisible file input
fileInput = L.DomUtil.create('input', 'hidden', container);
fileInput.type = 'file';
fileInput.multiple = 'multiple';
if (!this.options.formats) {
fileInput.accept = '.gpx,.kml,.geojson';
} else {
fileInput.accept = this.options.formats.join(',');
}
fileInput.style.display = 'none';
// Load on file change
fileInput.addEventListener('change', function () {
thisLoader.loadMultiple(this.files);
// reset so that the user can upload the same file again if they want to
this.value = '';
}, false);
L.DomEvent.disableClickPropagation(link);
L.DomEvent.on(link, 'click', function (e) {
fileInput.click();
e.preventDefault();
});
return container;
}
});
L.Util.FileLoader = FileLoader;
L.Util.fileLoader = function (map, options) {
return new L.Util.FileLoader(map, options);
};
L.Control.FileLayerLoad = FileLayerLoad;
L.Control.fileLayerLoad = function (options) {
return new L.Control.FileLayerLoad(options);
};
}, window));
<!DOCTYPE html>
<html lang="en">
<head>
<title>Leaflet Filelayer </title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/4.2.0/normalize.min.css">
<link rel="stylesheet" href="https://unpkg.com/leaflet#0.7.7/dist/leaflet.css">
<link rel="stylesheet" href="style.css">
<script src="https://unpkg.com/leaflet#1.2.0/dist/leaflet.js"></script>
<script src="https://unpkg.com/togeojson#0.14.2"></script>
<script src="https://unpkg.com/leaflet-filelayer#0.6.0"></script>
<script src="me.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="menu.js"></script>
<script src="index.js"></script>
</head>
<body>
<header>
<h1>A Visual Isarithmic Mapping Tool For Online Maps</h1>
<div id="controls" class="bar"></div>
<button class="menu-toggle">
<span class="bar"></span>
<span class="bar"></span>
<span class="bar"></span>
</button>
</header>
<main>
<div id="map" style="width: 100%; height: 100%; display: block;"></div>
</main>
<script>
var points = data:loaded;
L.geoJson(points).addTo(map);
</script>
</body>
</html>
I am using leaflet file layer plugin.I have added a kml file which includes some points. I want to do sth by using these points. But I don't know if the plugin saves this data or not. How can I use these points?
https://github.com/makinacorpus/Leaflet.FileLayer/issues/24
In the link you can see what I mentioned.

Google Map markers Infobox in exact same location

I am not a programmer or a developer. I am facing a problem that the google map infobox not display when they are in exact same location, (geocodezip) have a very good solution, however I don't know how to modify my code.
This is my code
(function ($) {
var settings;
var element;
var map;
var markers = new Array();
var markerCluster;
var clustersOnMap = new Array();
var clusterListener;
var methods = {
init: function (options) {
element = $(this);
var defaults = $.extend({
enableGeolocation: false,
pixelOffsetX : -145,
pixelOffsetY : -200
});
settings = $.extend({}, defaults, options);
google.maps.Map.prototype.setCenterWithOffset = function (latlng, offsetX, offsetY) {
var map = this;
var ov = new google.maps.OverlayView();
ov.onAdd = function () {
var proj = this.getProjection();
var aPoint = proj.fromLatLngToContainerPixel(latlng);
aPoint.x = aPoint.x + offsetX;
aPoint.y = aPoint.y + offsetY;
map.setCenter(proj.fromContainerPixelToLatLng(aPoint));
}
ov.draw = function () {
};
ov.setMap(this);
};
google.maps.visualRefresh = true;
google.maps.event.addDomListener(window, 'load', loadMap);
if (settings.filterForm && $(settings.filterForm).length !== 0) {
$(settings.filterForm).submit(function (e) {
var form = $(this);
var action = $(this).attr('action');
$.ajax({
type : 'GET',
url : action,
data : form.serialize(),
success: function (data) {
element.aviators_map('removeMarkers');
element.aviators_map('addMarkers', {
locations: eval(data.locations),
types : eval(data.types),
contents : eval(data.contents)
});
}
});
e.preventDefault();
});
}
if (options.callback) {
options.callback();
}
return $(this);
},
removeMarkers: function () {
for (i = 0; i < markers.length; i++) {
markers[i].infobox.close();
markers[i].marker.close();
markers[i].setMap(null);
}
markerCluster.clearMarkers();
$.each(clustersOnMap, function (index, cluster) {
cluster.cluster.close();
});
clusterListener.remove();
},
addMarkers: function (options) {
markers = new Array();
settings.locations = options.locations;
settings.contents = options.contents;
settings.types = options.types;
renderElements();
}
}
$.fn.aviators_map = function (method) {
// Method calling logic
if (methods[method]) {
return methods[ method ].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === 'object' || !method) {
return methods.init.apply(this, arguments);
} else {
$.error('Method ' + method + ' does not exist on Aviators Map');
}
};
function loadMap() {
var mapOptions = {
zoom : settings.zoom,
mapTypeId : google.maps.MapTypeId.ROADMAP,
scrollwheel : false,
draggable : true,
mapTypeControl : false,
panControl : false,
zoomControl : true,
zoomControlOptions: {
style : google.maps.ZoomControlStyle.SMALL,
position: google.maps.ControlPosition.LEFT_BOTTOM
}
};
if (settings.enableGeolocation) {
if (navigator.geolocation) {
browserSupportFlag = true;
navigator.geolocation.getCurrentPosition(function (position) {
initialLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
map.setCenter(initialLocation);
}, function () {
mapOptions.center = new google.maps.LatLng(settings.center.latitude, settings.center.longitude);
});
} else {
browserSupportFlag = false;
mapOptions.center = new google.maps.LatLng(settings.center.latitude, settings.center.longitude);
}
} else {
mapOptions.center = new google.maps.LatLng(settings.center.latitude, settings.center.longitude);
}
map = new google.maps.Map($(element)[0], mapOptions);
var dragFlag = false;
var start = 0, end = 0;
function thisTouchStart(e) {
dragFlag = true;
start = e.touches[0].pageY;
}
function thisTouchEnd() {
dragFlag = false;
}
function thisTouchMove(e) {
if (!dragFlag) {
return
}
end = e.touches[0].pageY;
window.scrollBy(0, ( start - end ));
}
var el = $('#map')[0];
if (el.addEventListener) {
el.addEventListener('touchstart', thisTouchStart, true);
el.addEventListener('touchend', thisTouchEnd, true);
el.addEventListener('touchmove', thisTouchMove, true);
} else if (el.attachEvent){
el.attachEvent('touchstart', thisTouchStart);
el.attachEvent('touchend', thisTouchEnd);
el.attachEvent('touchmove', thisTouchMove);
}
google.maps.event.addListener(map, 'zoom_changed', function () {
$.each(markers, function (index, marker) {
marker.infobox.close();
marker.infobox.isOpen = false;
});
});
renderElements();
$('.infobox .close').live('click', function () {
$.each(markers, function (index, marker) {
marker.infobox.close();
marker.infobox.isOpen = false;
});
});
}
function isClusterOnMap(clustersOnMap, cluster) {
if (cluster === undefined) {
return false;
}
if (clustersOnMap.length == 0) {
return false;
}
var val = false;
$.each(clustersOnMap, function (index, cluster_on_map) {
if (cluster_on_map.getCenter() == cluster.getCenter()) {
val = cluster_on_map;
}
});
return val;
}
function addClusterOnMap(cluster) {
// Hide all cluster's markers
$.each(cluster.getMarkers(), (function () {
if (this.marker.isHidden == false) {
this.marker.isHidden = true;
this.marker.close();
}
}));
var newCluster = new InfoBox({
markers : cluster.getMarkers(),
draggable : true,
content : '<div class="clusterer"><div class="clusterer-inner">' + cluster.getMarkers().length + '</div></div>',
disableAutoPan : true,
pixelOffset : new google.maps.Size(-21, -21),
position : cluster.getCenter(),
closeBoxURL : "",
isHidden : false,
enableEventPropagation: true,
pane : "mapPane"
});
cluster.cluster = newCluster;
cluster.markers = cluster.getMarkers();
cluster.cluster.open(map, cluster.marker);
clustersOnMap.push(cluster);
}
function renderElements() {
$.each(settings.locations, function (index, location) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(location[0], location[1]),
map : map,
icon : settings.transparentMarkerImage
});
marker.infobox = new InfoBox({
content : settings.contents[index],
disableAutoPan : false,
maxWidth : 0,
pixelOffset : new google.maps.Size(settings.pixelOffsetX, settings.pixelOffsetY),
zIndex : null,
closeBoxURL : "",
infoBoxClearance : new google.maps.Size(1, 1),
position : new google.maps.LatLng(location[0], location[1]),
isHidden : false,
pane : "floatPane",
enableEventPropagation: false
});
marker.infobox.isOpen = false;
marker.marker = new InfoBox({
draggable : true,
content : '<div class="marker ' + settings.types[index] + '"><div class="marker-inner"></div></div>',
disableAutoPan : true,
pixelOffset : new google.maps.Size(-21, -58),
position : new google.maps.LatLng(location[0], location[1]),
closeBoxURL : "",
isHidden : false,
pane : "floatPane",
enableEventPropagation: true
});
marker.marker.isHidden = false;
marker.marker.open(map, marker);
markers.push(marker);
google.maps.event.addListener(marker, 'click', function (e) {
var curMarker = this;
$.each(markers, function (index, marker) {
// if marker is not the clicked marker, close the marker
if (marker !== curMarker) {
marker.infobox.close();
marker.infobox.isOpen = false;
}
});
if (curMarker.infobox.isOpen === false) {
curMarker.infobox.open(map, this);
curMarker.infobox.isOpen = true;
map.setCenterWithOffset(curMarker.getPosition(), 100, -120);
} else {
curMarker.infobox.close();
curMarker.infobox.isOpen = false;
}
});
});
markerCluster = new MarkerClusterer(map, markers, {
gridSize: 40,
styles: [
{
height : 42,
url : settings.transparentClusterImage,
width : 42,
textColor: 'transparent'
}
]
});
clustersOnMap = new Array();
clusterListener = google.maps.event.addListener(markerCluster, 'clusteringend', function (clusterer) {
var availableClusters = clusterer.getClusters();
var activeClusters = new Array();
$.each(availableClusters, function (index, cluster) {
if (cluster.getMarkers().length > 1) {
activeClusters.push(cluster);
}
});
$.each(availableClusters, function (index, cluster) {
if (cluster.getMarkers().length > 1) {
var val = isClusterOnMap(clustersOnMap, cluster);
if (val !== false) {
val.cluster.setContent('<div class="clusterer"><div class="clusterer-inner">' + cluster.getMarkers().length + '</div></div>');
val.markers = cluster.getMarkers();
$.each(cluster.getMarkers(), (function (index, marker) {
if (marker.marker.isHidden == false) {
marker.marker.isHidden = true;
marker.marker.close();
}
}));
} else {
addClusterOnMap(cluster);
}
} else {
// Show all markers without the cluster
$.each(cluster.getMarkers(), function (index, marker) {
if (marker.marker.isHidden == true) {
marker.marker.open(map, this);
marker.marker.isHidden = false;
}
});
// Remove old cluster
$.each(clustersOnMap, function (index, cluster_on_map) {
if (cluster !== undefined && cluster_on_map !== undefined) {
if (cluster_on_map.getCenter() == cluster.getCenter()) {
// Show all cluster's markers/
cluster_on_map.cluster.close();
clustersOnMap.splice(index, 1);
}
}
});
}
});
var newClustersOnMap = new Array();
$.each(clustersOnMap, function (index, clusterOnMap) {
var remove = true;
$.each(availableClusters, function (index2, availableCluster) {
if (availableCluster.getCenter() == clusterOnMap.getCenter()) {
remove = false;
}
});
if (!remove) {
newClustersOnMap.push(clusterOnMap);
} else {
clusterOnMap.cluster.close();
}
});
clustersOnMap = newClustersOnMap;
});
}
})(jQuery);
and This is geocodezip code
Google Maps Multiple markers with the exact same location Not working
Many Many Thanks
That solution is great, but I'd take a look at using the Overlapping Marker Spiderfier library to handle markers in the same location. You can use this in conjunction with the marker clusterer library, without any issues. This way you also don't lose the ability to see how many markers are actually in that same location - and it gives you a great UI in my opinion.
To use Overlapping Marker Spiderfier, include the script file before your main js file in your html. Then in your js, create an instance of the OverlappingMarkerSpiderfier object:
var oms = new OverlappingMarkerSpiderfier(map);
/*in your case I'd do this after you initialize the `map` object,
*and declare the `oms` globally, like you do with your other global objects
*/
Then when the markers are created, you want to add the marker to the oms object via the addMarker() method. So, in your case add the following line to the renderElements() function after the click event listener you declare for the marker:
oms.addMarker(marker);
Lastly, make sure to also clear the markers from the oms object when the removeMarkers() function in your code is called by adding the following to that function:
oms.clearMarkers();

Google Maps API issue with IE8

I'm writing some code with the Google Maps API, it works fine in all browsers (FF, IE9, Chrome) but IE8 or below, I have assigned the map to a global variable called Map, which gets populated but when the addMarker function gets called the Map global is null in IE8, but the addMarker function does work when I call it from the locator function, I have included all these functions below.
var GoogleMaps = {};
var Map = null;
var init = (function () {
"use strict";
var MapType = null;
var ZoomLevel = null;
var ControlPos = null;
var ControlSize = null;
var myLatLong = null;
var Geocoder;
var result = null;
GoogleMaps.setup = function (options) {
myLatLong = new google.maps.LatLng(24.886436490787712, -70.26855468754);
if (google.loader.ClientLocation) {
myLatLong = new google.maps.LatLng(
google.loader.ClientLocation.latitude,
google.loader.ClientLocation.longitude);
} else if (options.Lat !== null && options.Long !== null) {
options.Location = new google.maps.LatLng(options.Lat, options.Long);
} else {
// Else centre to UK
options.Location = new google.maps.LatLng(52.961875, -1.419433);
}
if (options.MapType.toUpperCase() === 'ROADMAP') {
MapType = google.maps.MapTypeId.ROADMAP;
} else if (options.MapType.toUpperCase() === 'TERRAIN') {
MapType = google.maps.MapTypeId.TERRAIN;
} else if (options.MapType.toUpperCase() === 'HYBRID') {
MapType = google.maps.MapTypeId.HYBRID;
} else {
MapType = google.maps.MapTypeId.SATELLITE;
}
// Check zoom level, if not set then set to zoom level 8.
if (options.ZoomLevel) {
ZoomLevel = options.ZoomLevel;
} else {
ZoomLevel = 8;
}
var mapOptions = {
center: myLatLong,
zoom: ZoomLevel,
mapTypeId: MapType
};
var mapDiv = document.getElementById('canvas');
// Map gets initiated here
window.Map = new google.maps.Map(mapDiv, mapOptions);
delete options.MapType;
delete options.Lat;
delete options.Long;
delete options.ZoomLevel;
};
GoogleMaps.addMarker = function (options) {
var Location = null;
var Animation = null;
var Title = null;
var Draggable = null;
var Content = null;
var InfoWindow = null;
var Flat = null;
var Clickable = null;
if (options.lat !== null && options.long !== null) {
Location = new google.maps.LatLng(options.lat, options.long);
;
} else {
Location = myLatLong;
}
if (typeof(options.position) !== "undefined") {
Location = options.position;
}
if (options.animation.toUpperCase() === 'BOUNCE') {
Animation = google.maps.Animation.BOUNCE;
} else if (options.animation.toUpperCase() === 'DROP') {
Animation = google.maps.Animation.DROP;
} else {
Animation = google.maps.Animation.NONE;
}
if (options.draggable !== null && options.draggable === 'true') {
Draggable = true;
} else {
Draggable = false;
}
if (options.title !== null) {
Title = options.title;
} else {
Title = null;
}
if (options.content !== null) {
Content = options.content;
InfoWindow = new google.maps.InfoWindow({
content: Content
});
}
if (options.flat !== null && options.flat === 'true') {
Flat = true;
} else {
Flat = false;
}
if (options.clickable !== null && options.clickable === 'true') {
Clickable = true;
} else {
Clickable = false;
}
// Gets used in this section
var Marker = new google.maps.Marker({
position: Location,
map: window.Map,
animation: Animation,
draggable: Draggable,
title: Title,
flat: Flat,
clickable: Clickable,
zIndex: 1
});
// and sets map here
Marker.setMap(window.Map);
if (options.content !== null) {
google.maps.event.addListener(Marker, 'click', function (e) {
InfoWindow.open(window.Map, this);
google.maps.event.addListener(window.Map, 'click', function (e) {
InfoWindow.close(window.Map, window.Marker);
});
});
}
google.maps.event.addListener(Marker, 'dragend', function (e) {
});
delete options.lat;
delete options.long;
delete options.animation;
delete options.title;
delete options.content;
delete options.flat;
delete options.draggable;
delete options.clickable;
};
GoogleMaps.Locator = function (result) {
var address = null;
Geocoder = new google.maps.Geocoder();
address = result;
Geocoder.geocode({ 'address': address }, function (response, status) {
if (status === google.maps.GeocoderStatus.OK) {
window.Map.setCenter(response[0].geometry.location);
var Location = new google.maps.LatLng(response[0].geometry.location.Xa, response[0].geometry.location.Ya);
var markerOptions = {
animation: "drop",
draggable: "true",
content: 'Hello World!',
title: "Hello",
position: Location
};
GoogleMaps.addMarker(markerOptions);
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
};
Below is how I am calling the functions:
var markerOptions = {
lat: 52.48278,
long: -0.892089,
animation: "drop",
draggable: "true",
content: 'Hello World!',
title: "Click Me"
};
google.maps.event.addDomListener(window, 'load', function () { GoogleMaps.setMarker(markerOptions) });
google.maps.event.addDomListener(window, 'load', function () { GoogleMaps.Locator('London') });
Thanks for any help.
I resolved the problem like this.
<meta http-equiv=”X-UA-Compatible” content=”IE=EmulateIE7; IE=EmulateIE9″/>
Try changing this line in your setup
window.Map = new google.maps.Map(mapDiv, mapOptions);
to just
Map = new google.maps.Map(mapDiv, mapOptions);
This way you accessing the global variable declared.
when is GoogleMaps.setup called? Right now it looks like depending on the browser it can be called after functions attached by
google.maps.event.addDomListener(window, 'load', function () { ... });
and that's why map is not set when you call addMarker, but is already initialized when you receive callback from
Geocoder.geocode(...)
To fix this make sure that GoogleMaps.setup is called before addMarker.
IE8 has always meant trouble. :-) Try adding the following meta tag at the beginning of your <head> section:
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" />
Description here:
http://blogs.msdn.com/b/ie/archive/2008/06/10/introducing-ie-emulateie7.aspx

Categories