I have a JSON with different points. Each point has a different fields, like lon1 , lat1, lon2, lat2.
For each point I draw a line from point 1 to point 2.
By means of a for I perform this operation for each point and I draw different polylines in the map.
The problem is that when I activate or deactivate the layer, only the last drawn line is hidden, not all lines.
In the map you can see all the lines, but it seems that in the layer it overwrites and deletes the last line generated.
Code:
for (var i = 0; i < json_ARAPointsPRU_0.features.length; i++) {
var Lon1 = json_ARAPointsPRU_0.features[i].properties['Lon(d.dd)'];
var Lat1 = json_ARAPointsPRU_0.features[i].properties['Lat(d.dd)'];
var Lon2 = json_ARAPointsPRU_0.features[i].properties['LON2'];
var Lat2 = json_ARAPointsPRU_0.features[i].properties['LAT2'];
// array of coordinates
var mylatlngs = [
[Lat1, Lon1],
[Lat2, Lon2]
];
// draw a polyline in the map
var polilineas = L.polyline(mylatlngs, {
color: 'blue'
});
polilineas.addTo(map);
// add " polilineas" into other layer
var Velocidad2D = new L.LayerGroup();
Velocidad2D.addLayer(polilineas);
// Velocidad2D.addLayer(cabezas); Possibility to add arrow head
}
// Code to LAYER CONTROL
var gropedOverlayslehen = {
"Vel 2D": Velocidad2D
}
var layerControl = L.control.layers(basemaps, gropedOverlayslehen);
layerControl.addTo(map);
You need to put var Velocidad2D = new L.LayerGroup(); to the outside of the loop, else you overwrite it everytime.
var Velocidad2D = new L.LayerGroup();
for (var i = 0; i < json_ARAPointsPRU_0.features.length; i++) {
var Lon1 = json_ARAPointsPRU_0.features[i].properties['Lon(d.dd)'];
var Lat1 = json_ARAPointsPRU_0.features[i].properties['Lat(d.dd)'];
var Lon2 = json_ARAPointsPRU_0.features[i].properties['LON2'];
var Lat2 = json_ARAPointsPRU_0.features[i].properties['LAT2'];
// array of coordinates
var mylatlngs = [
[Lat1, Lon1],
[Lat2, Lon2]
];
// draw a polyline in the map
var polilineas = L.polyline(mylatlngs, {
color: 'blue'
});
polilineas.addTo(map);
// add " polilineas" into other layer
Velocidad2D.addLayer(polilineas);
// Velocidad2D.addLayer(cabezas); Possibility to add arrow head
}
// Code to LAYER CONTROL
var gropedOverlayslehen = {
"Vel 2D": Velocidad2D
}
var layerControl = L.control.layers(basemaps, gropedOverlayslehen);
layerControl.addTo(map);
Related
I am using google maps api to create a store locator with clusters and I am referring the marker cluster api.
I wanted to get the list of stores with in a markercluster rather than returning marker cluster with pins/markers. Please find the below code -
google.maps.event.addListener(mapsCore.mapsVar.markerCluster, 'clusterclick', function(cluster) {
var content = "";
// Convert lat/long from cluster object to a usable MVCObject
var info = new google.maps.MVCObject;
info.set('position', cluster.center_);
//----
//Get markers
console.log(cluster.getSize());
var markers = cluster.getMarkers();
var x = {};
$(mapsCore.mapsVar.totalResults.Result).each(function(k, v) {
$(markers).each(function(km, vm) {
if (parseFloat(v.LAT) == parseFloat(markers[km].position.lat()) && parseFloat(v.LON) == parseFloat(markers[km].position.lng())) {
// locArr[k] = { lat: parseFloat(v.CounterLatitude), lng: parseFloat(v.CounterLongitude) };
x.Counter_ID = v.Counter_ID;
x.Counter_Name = v.Counter_Name;
x.Counter_Zip_code = v.Counter_Zip_code;
x.Address_1 = v.Address_1;
x.Address_2 = v.Address_2;
x.Province = v.Province;
x.City = v.City;
x.Area = v.Area;
x.SubArea = v.SubArea;
x.Counter_Tel = v.Counter_Tel;
x.Counter_Email = v.Counter_Email;
x.Open_Time = v.Open_Time;
x.Close_Time = v.Close_Time;
x.LAT = v.LAT;
x.LON = v.LON;
x.MR_FLG = v.MR_FLG;
mapsCore.mapsVar.clusterDetail.Results.push(x);
x = {};
}
});
});
});
As a workaround you can set a custom image to an transparent png and text size to 0, that way it'll be invisible on the map.
cluster.setStyles({
url: your_path/transparent.png,
height: 20,
width: 20,
textSize: 0
});
Alternatively you can try and see if setting the image height and width to 0 works.
All,
thanks for your help for formatting my code and comments any way I found the solution for it. I will attach the spinet of code below
google.maps.event.addListener(mapsCore.mapsVar.markerCluster, 'clusterclick', function(cluster) {
var content = '';
// Convert lat/long from cluster object to a usable MVCObject
var info = new google.maps.MVCObject;
info.set('position', cluster.center_);
//----
//Get markers
console.log(cluster.getSize());
var markers = cluster.getMarkers();
var x = {};
mapsCore.mapsVar.clusterDetail.Counters.length = 0;
$(mapsCore.mapsVar.totalResults.Counters).each(function(k, v) {
$(markers).each(function(km, vm) {
console.log(parseFloat(v.CounterLatitude) == parseFloat(vm.position.lat()) && parseFloat(v.CounterLongitude) == parseFloat(vm.position.lng()));
if (parseFloat(v.CounterLatitude) == parseFloat(vm.position.lat())) {
// locArr[k] = { lat: parseFloat(v.CounterLatitude), lng: parseFloat(v.CounterLongitude) };
x.CounterCode = v.CounterCode;
x.CounterName = v.CounterName;
x.CounterZipCode = v.CounterZipCode;
x.AddressLine1 = v.AddressLine1;
x.AddressLine2 = v.AddressLine2;
x.Province = v.Province;
x.City = v.City;
x.Area = v.Area;
x.SubArea = v.SubArea;
x.CounterPhoneNumber = v.CounterPhoneNumber;
x.CounterEmailAddress = v.CounterEmailAddress;
x.CounterOpenTime = v.CounterOpenTime;
x.CounterCloseTime = v.CounterCloseTime;
x.CounterLatitude = v.CounterLatitude;
x.CounterLongitude = v.CounterLongitude;
x.IsMagicRingAvailable = v.IsMagicRingAvailable;
mapsCore.mapsVar.clusterDetail.Counters.push(x);
x = {};
}
});
});
console.log(mapsCore.mapsVar.clusterDetail);
var template = $.templates("#mapslist");
var output = template.render(mapsCore.mapsVar.clusterDetail);
$(".store-list-section").html(output);
});
Always need to reset the array of object like -
mapsCore.mapsVar.clusterDetail.Counters.length = 0;
I'm trying to remove an array of GeoJson layers from Google Maps using the turf.js library for smoothing of the poly-lines.
I can create the layer fine and add them to the map, but when I try and remove the layers I get the following error code:
Uncaught TypeError: a.getId is not a function
To add the layers I do this, looping through my GeoJson file...
else if(Type==="LineString" && Pype==="isobar") {
//DO ISOBARS STUFF=================================
//GET LNG/LAT======================================
CorrLEN = dataID1.features[i].geometry.coordinates.length;
var Corrds =[];
var Corrs =[];
var LNGLAT ={};
var CORRS = new Object();
var x=0;
for (x=0;x<CorrLEN;x++){
var a = x-1;
LNGLAT = (dataID1.features[i].geometry.coordinates[x]);
Corrds.push(LNGLAT);
}
//=================================================================
//GET COLOUR INFO===================================================
var STCL = dataID1.features[i].properties.strokeColor;
var STOP = dataID1.features[i].properties.strokeOpacity;
var STSW = dataID1.features[i].properties.strokeWeight;
//=================================================================
LL = turf.linestring(Corrds);
curved = turf.bezier(LL,20000, 0.35);
curved.properties = {weight:STSW,color:STCL};
map.data.setStyle(function(feature) {
return {strokeWeight:feature.getProperty('weight'),
strokeColor: feature.getProperty('color')
};
});
IsoBars.push(curved);
I then use the following functions to add or remove the layers
//SHOW ISOBARS (works fine)
function ShowIsoBars() {
for (var i = 0; i < IsoBars.length; i++) {
map.data.addGeoJson(IsoBars[i]);
}}
//HIDE ISOBARS (Gets the error) Uncaught TypeError: a.getId is not a function
function HideIsoBars() {
for (var i = 0; i < IsoBars.length; i++) {
map.data.remove(IsoBars[i]);
}}
Many thanks in advance,
I found a solution by taking the new smoothed coordinates and then using them in a new google.maps.Polyline like so
var Path =[];
var x=0;
for (x=0;x<CorrLEN;x++){
Path.push(new google.maps.LatLng(curved.geometry.coordinates[x][1],curved.geometry.coordinates[x][0]));
}
var IsoBar = new google.maps.Polyline({
path: Path,
geodesic: true,
strokeColor: STCL,
strokeOpacity: STOP,
strokeWeight: STSW
});
IsoBars.push(IsoBar);
And then I can use the the following functions to show or hide the layers
function ShowIsoBars() {
for (var i = 0; i < IsoBars.length; i++) {
IsoBars[i].setMap(map);
}}
function HideIsoBars() {
for (var i = 0; i < IsoBars.length; i++) {
IsoBars[i].setMap(null);
}}
I found rather than removing all objects from the layer. It was easier to destroy and recreate the layer, which circumvents the error:
//Remove layer from map if it exists
if (mapLayer != null) {
mapLayer.setMap(null);
}
//create new layer
mapLayer = new window.google.maps.Data({ map: googleMap });
I want to display multiple polylines from an XML file:
<lines>
<line>
<linePoint lat="47.608940" lng="-122.340141"/>
<linePoint lat="47.613590" lng="-122.344391"/>
<linePoint lat="47.624561" lng="-122.356445"/>
</line>
<line>
<linePoint lat="47.616600" lng="-122.344491"/>
<linePoint lat="47.627661" lng="-122.356545"/>
</line>
</lines>
I believe that the script should iterate twice - the outer loop going through line elements and the inner loop going through linePoint elements within each line.
But it seems that my script dumps all 5 linePoint into a single polyline instead of creating 2 polylines.
downloadUrl("createXML.php", function(data) {
var xml = data.responseXML;
var line = xml.documentElement.getElementsByTagName("line");
// Read each line
for (var a = 0; a < line.length; a++) {
var linePoint = xml.documentElement.getElementsByTagName("linePoint");
var path = [];
// Read markers on each line
for (var i = 0; i < linePoint.length; i++) {
var lat = parseFloat(linePoint[i].getAttribute("lat"));
var lng = parseFloat(linePoint[i].getAttribute("lng"));
var point = new google.maps.LatLng(lat,lng);
path.push(point);
}
var polyline = new google.maps.Polyline({
path: path
});
polyline.setMap(map);
}
});
Can someone please point out what I'm overlooking?
Yes, that is because you just extract all <linePoint>'s in one chunk by getElementsByTagName("linePoint") (elements in plural). Iterate over <line>'s and for each <line> iterate over its <linePoint>'s :
function showPolyLines() {
var parser = new DOMParser();
var xml = parser.parseFromString(responseXML, "application/xml");
var line = xml.querySelectorAll("line");
for (var l = 0; l < line.length; l++) {
var path = [],
linePoints = line[l].querySelectorAll('linePoint');
for (var p = 0; p < linePoints.length; p++) {
var linePoint = linePoints[p],
lat = parseFloat(linePoint.getAttribute("lat")),
lng = parseFloat(linePoint.getAttribute("lng")),
point = new google.maps.LatLng(lat, lng);
path.push(point);
}
var polyline = new google.maps.Polyline({
path: path,
//just to be sure the lines actually is shown on the map :)
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 2
});
polyline.setMap(map);
}
}
I am using a DOMParser to substitute xml.documentElement because I dont have a real responseXML in my fiddle test, but they are practically the same.
demo -> http://jsfiddle.net/9sqastj1/
I want to get NE and SW corners of a set of markers on a google map. Here I iterate over each marker. Does google or javascript provide a function that gets this with less iteration?
function fnSetBounds(){
var lowLat = 90;
var highLat = -90;
var lowLng = 180;
var highLng = -180;
for (var i = 0; i < myMarkers.length; i++) {
var myLat = myMarkers[i].position['k'];
var myLng = myMarkers[i].position['B'];
// catch low LAT
if (lowLat > myLat){
lowLat = myLat;
}
// catch high LAT
if (highLat < myLat) {
highLat = myLat;
}
// catch low LNG
if (lowLng > myLng){
lowLng = myLng;
}
// catch high lng
if (highLng < myLng) {
highLng = myLng;
}
}
var southWestCorner = new google.maps.LatLng(highLat, lowLng);
var northEastCorner = new google.maps.LatLng(lowLat, highLng);
var bounds = new google.maps.LatLngBounds();
bounds.extend(southWestCorner);
map.fitBounds(bounds);
bounds.extend(northEastCorner);
map.fitBounds(bounds);
}
I would do it this way, add all the positions to an empty bounds:
function fnSetBounds(){
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < myMarkers.length; i++) {
bounds.extend(myMarkers[i].getPosition());
}
map.fitBounds(bounds);
}
These are my coordinates of Selected diagonal points, will be more when selected points are more.
1: 25.312063043186914 2: 55.30672073364258
1: 25.24096949112138 2: 55.40525436401367
1: 25.224509592006314 2: 55.3462028503418
1: 25.22513076073063 2: 55.281314849853516
1: 25.27822894908031 2: 55.25899887084961
below is my current mysql query not giving me perfect result between selected diagonal.any help??
SELECT
*
FROM
tbl_custom
WHERE latitude <= 25.312063043186914
AND latitude >= 25.224509592006314
AND longitude <= 55.40525436401367
AND longitude >= 55.25899887084961
To eliminate the points within your bounding box query but not within polygon you require to use Point in Polygon algorithm.
The easiest way to do this is to have the coordinates in arrays. These can be used to find max and min coordinates for the query and for parameters for pointInPolygon() function.
function pointInPolygon(polySides,polyX,polyY,x,y) {
var j = polySides-1 ;
oddNodes = 0;
for (i=0; i<polySides; i++) {
if (polyY[i]<y && polyY[j]>=y || polyY[j]<y && polyY[i]>=y) {
if (polyX[i]+(y-polyY[i])/(polyY[j]-polyY[i])*(polyX[j]-polyX[i])<x) {
oddNodes=!oddNodes;
}
}
j=i; }
return oddNodes;
}
In your Map code using jQuery getJSON()
var polySides = 4;//number of points in polygon
//horizontal Latitude coordinates of polygon
var polyLat = new Array();
polyLat[0] = 51.5;
polyLat[1] = 51.5;
polyLat[2] = 52.5;
polyLat[3] = 53;
polyLat[4] = 51.5;//First point repeated to close polygon
//vertical Longitude coordinates of polygon
var polyLng = new Array();
polyLng[0] = 0.5;
polyLng[1] = -1.9;
polyLng[2] = -1;
polyLng[3] = 0.6;
polyLng[4] = 0.5;
//Coordinates for bounding box
var maxLat = Math.max.apply(null,polyLat);
var minLat = Math.min.apply(null,polyLat);
var maxLng = Math.max.apply(null,polyLng);
var minLng = Math.min.apply(null,polyLng);
//Using jQuery
var url = "yourFile .php";
url +="?maxLat="+maxLat +"&minLat="+minLat +"&maxLng="+maxLng +"&minLng="+minLng;
$.getJSON(url,function(data) {
$.each(data.marker,function(i,dat){
if (pointInPolygon(polySides,polyLat,polyLng,dat.lat,dat.lng)){
var latlng = new google.maps.LatLng(dat.lat,dat.lng);
addMarker(latlng,dat.name);
bounds.extend(latlng);
}
});
map.fitBounds(bounds);
});
Map obtained using Bounding Box and Point in Polygon.