Leaflet rendering one polygon in a list of polygons - javascript

I have a leaflet map with django. I'm passing geojson from a database. For some reason, I'm not getting any errors, but it's only rendering one polygon instead of around 3,000. Everything else seems to be working correctly.
It's technically not a multipolygon since there aren't shapes inside this shape but a bunch of shapes rendered in the same place.
function initmap(){
var map = new L.map('map',{
center: [1.0,1.0],
layers: [osmLayer,markers,parcelLayer],
minZoom: 1,
zoom: 3 }
).setView([lat,long],13 );
}
var osmLayer = new L.tileLayer( 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap',
subdomains: ['a','b','c']
});
var markers = new L.FeatureGroup();
var parcelFeature = ['{"geometry": {"type": "Polygon", "coordinates": [[[a,b],[c,d],[e,f],[g,h]]]}, "type": "Feature"}',
'{"geometry": {"type": "Polygon", "coordinates": [[[i,j],[k,l],[m,n],[o,p]]], "type": "Feature"}'];
parcelFeature = JSON.parse(parcelFeature[0]);
var parcelLayer = L.geoJson([parcelFeature],{
style : {
"color": "#000000",
"weight": 3,
"opacity": 10.65
}
});
parcelLayer.on("loaded", function(e) {map.fitBounds(e.target.getBounds());} );
//marker icon
var ceIcon = L.icon({
iconUrl: "/static/maps/leaflet/images/somepng.png",
iconSize: [45,45],
iconAnchor: [0, 0],
popupAnchor: [-3, -76]
});
//add markers
marker = new L.marker([lat,long], {icon:ceIcon});
markers.addLayer(marker);
marker = new L.marker([lat,long], {icon:ceIcon});
markers.addLayer(marker);
marker = new L.marker([lat,long], {icon:ceIcon});
markers.addLayer(marker);
marker = new L.marker([lat,long], {icon:ceIcon});
markers.addLayer(marker);
initmap();

What I did was pass this through django as a json and then splitting in javascript each json item and adding it to a new list.
var parcelFeature = [];
var parcel_json = {{ parcel_json|safe }};
for(i = 0; i < parcel_json.length; i++){
var pjson = parcel_json[i];
pjson = JSON.parse(pjson);
parcelFeature.push(pjson);
}
After this I used the default L.geoJson layer and it rendered correctly. Not sure the issue.
var parcelLayer = L.geoJson(parcelFeature,
{ style :{
"color": "#000000",
"weight": 1,
"opacity": 100},
"fillColor":"#FFFFFF",
onEachFeature: function(feature, layer) {
// does this feature have a property named popupContent?
if (feature.properties && feature.properties.popupContent) {
layer.bindPopup(feature.properties.popupContent);
console.dir(feature.properties.popupContent);
} }
});

Related

Javascript Function & Variable Scope using geolocation

I'm trying to use geolocation to get my current position, which inserts the lat and lon into the centre point of a map. I know that geolocation is asynchronous, so I have to get that value, then call another function for this to pass forward. I am not getting the object mymap created for some reason.
<script>
function foundLocation(pos) {
setMyLocation(pos.coords.latitude, pos.coords.longitude)
};
function noLocation() {
document.getElementById("warning").innerHTML = "Could not find your location";
};
function setMyLocation(myLat, myLon) {
L.marker([ myLat, myLon ], {icon: homeIcon}).bindPopup("You Are Here").addTo(coolPlaces);
var mymap = L.map('mapid', {
center: [ myLat, myLon ],
minZoom: 2,
maxZoom: 18,
zoom: 15,
layers: [mymarkers]
});
};
navigator.geolocation.getCurrentPosition(foundLocation, noLocation);
<snip other JS irrelevant stuff>
</script>
Is there a way I can get those two variables out of the function and create the mymap object? I'm not well versed in JS and its restrictions.
The above code results in no map generated. I have to take mymap outside the geolocation functions for this to happen. The issue is that I don't know how to send myLat and myLon outside to that declaration.
Kudos to #espascarello: All the map functionality inside the success function foundLocation(pos).
Update: The problem is above. Read it. Putting every map function inside foundLocation(pos) worked fine. There's no use for any map function if these two variables are not found.
myLat = 0
myLon = 0
mymap = ""
function foundLocation(pos) {
myLat = pos.coords.latitude;
myLon = pos.coords.longitude;
// setMyLocation(pos.coords.latitude, pos.coords.longitude)
var homeIcon = L.icon({
iconUrl: '/img/house_marker.png',
iconSize: [24, 24],
iconAnchor: [12, 24],
popupAnchor: [0, -24]
});
var mymarkers = L.layerGroup([
L.marker([ myLat, myLon ], {icon: homeIcon}).bindPopup("You Are Here"),
<%= #markers %>
]);
var mymap = L.map('mapid', {
center: [ myLat,myLon ],
minZoom: 2,
maxZoom: 18,
zoom: 15,
layers: [mymarkers]
});
L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpejY4NXVycTA2emYycXBndHRqcmZ3N3gifQ.rJcFIG214AriISLbB6B5aw', {
attribution: 'Map data © OpenStreetMap Imagery © Mapbox',
id: 'mapbox.streets'
}).addTo(mymap);
L.control.layers(mymarkers).addTo(mymap);
};
function noLocation() {
document.getElementById("warning").innerHTML = "Could not find your location";
};
function setMyLocation(pushLat, pushLon) {
alert("inside setMyLocation");
myLat = pushLat;
myLon = pushLon;
// var mymap = L.map('mapid', {
// center: [ myLat, myLon ],
// minZoom: 2,
// maxZoom: 18,
// zoom: 15,
// layers: [mymarkers]
// });
};
navigator.geolocation.getCurrentPosition(foundLocation, noLocation);

Google Maps & Turf.js Polyline Integration

I am working on an example google maps and turf js integration. I added the line with GeoJson data.Working snippet is attached. But I want to create a polyline out of turf line positions.
for (var j = 0; j < line.geometry.coordinates.length; j++) {
var wp = new google.maps.LatLng(line.geometry.coordinates[j][1], line.geometry.coordinates[j][0])
path.push(wp);
}
I tried to create a path then create my polyline based on this path but couldn't manage to create a path out of turf line arrays.
Any ideas how can I do this?
Thanks in advance!
var path = [];
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 2,
maxZoom: 8,
minZoom: 1,
center: {
lat: 0,
lng: -180
},
streetViewControl: false,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var line = {
"type": "Feature",
"properties": { "line": "on" },
"geometry": {
"type": "LineString",
"coordinates": [
[-122.214, 37.772],
[-157.821, 21.291],
[178.431, -18.142],
[153.027, -27.467]
]
}
};
map.data.addGeoJson(line);
var point = turf.point([185.431, -4.542]);
var marker = new google.maps.Marker({
position: new google.maps.LatLng(point.geometry.coordinates[1], point.geometry.coordinates[0]),
map: map,
});
html,
body,
#map {
height: 100%;
width: 100%;
padding: 0px;
margin: 0px;
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<script src="https://npmcdn.com/#turf/turf#4.7.2/turf.min.js"></script>
<div id="map"></div>
You need to create a polyline and add it to the map:
var polyline = new google.maps.Polyline({
path: path
});
polyline.setMap(map);
I solved it, I just didn't see it...
$.each(line.geometry.coordinates, function (key) {
var wp = { lat: line.geometry.coordinates[key][1], lng: line.geometry.coordinates[key][0] }
path.push(wp);
});

Loading GeoJSON into Mapbox

When I use GeoJSON inside the HTML it works, but when I try to load externally it doesn't.
My HTML file and GeoJSON file are in the same folder in site.
I try to open picture popups with markers.
Thanks a lot!
L.mapbox.accessToken = 'lalalalala';
var southWest = L.latLng(40.875557, 29.235992),
northEast = L.latLng(41.277226, 28.749847),
bounds = L.latLngBounds(southWest, northEast);
var map = L.mapbox.map('map', 'mapbox.light', {
maxBounds: bounds,
maxZoom: 19,
minZoom: 11
});
var myLayer = L.mapbox.featureLayer()
.loadURL('http://terkedilmisarabalar.mudurlugu.org/geojson/terkedilmisarabalar.geojson')
.on('ready', function() {
myLayer.eachLayer(function(layer) {
map.fitBounds(myLayer.getBounds());
layer.bindPopup(layer.features.properties.name);
});
})
.addTo(map);
myLayer.setGeoJSON(geojson);
myLayer.on('onclick', function(e) {
e.layer.openPopup();
});
myLayer.on('onrelease', function(e) {
e.layer.closePopup();
});
Here is an example GeoJSON file:
{
type: 'FeatureCollection',
features: [
{
"type": "Feature",
"properties": {
"name": "Acıbadem Cd. No:117",
"description": "<img src=\"https://lh3.googleusercontent.com/DkEl65k9kZAtvPdf9HuE22aIAJKUKBDtiL0m5vZBRqn9nVsgcQIQYdi03gt5yhOKcrEvTQpctu_xnLVfhzzt6Tr3fGtsxuIJSqPrf7R9p-0faSL-YRxTzyn44B8KVB8\" height=\"200\" width=\"auto\" /><br><br>",
"gx_media_links": "https://lh6.googleusercontent.com/fmIjm4ynkTWSkmzcOfoMCoVgnm6h9pQ8KINgHqhjx-ZNQMrT05NqsZo2Lv5d6FwFFakmqOzl_ruRKvu34jbC96U3nKaxlu0sul6W4qXU1ily4PNbLCQTsR2BGKOxervb"
},
"geometry": {
"coordinates": [
29.045881,
41.005992,
0
],
"type": "Point"
}
}

How determine if array is polygon or multypolygon reading from GeoJson?

Found this example to show a simple polygon, but I tried to show coutries with complex polygon (multipolygon for something countries) Let me show the way
Example:
"type": "Feature",
"properties": {
"Name": "Country_whit_multiples_polygons",
"Description": ""
},"geometry": {
"type": "MultiPolygon",
"coordinates": [
[
[-94.963194, 39.316858],
[-94.959670, 39.321990],
[-94.955570, 39.316610],
[-94.963194, 39.316858]
],
[
[-35, 34],
[-41, 37],
[-43, 38],
[-25, 39]
]
]
}
var sector_data = {
"type": "FeatureCollection",
"features": [{
"type": "Feature",
"properties": {
"Name": "Country_1",
"Description": ""
},
"geometry": {
"type": "Polygon",
"coordinates": [
[
[-94.963194, 39.316858],
[-94.959670, 39.321990],
[-94.955570, 39.316610],
[-94.963194, 39.316858]
]
]
}
}, {
"type": "Feature",
"properties": {
"Name": "COuntry_2",
"Description": ""
},
"geometry": {
"type": "Polygon",
"coordinates": [
[
[-94, 36],
[-94, 35],
[-95, 34],
[-98, 32],
[-90, 31]
]
]
}
}]
};
var map;
function initialize() {
var kansas_city = new google.maps.LatLng(39.00495613,-94.64780668);
var mapOptions = {
zoom: 10,
center: kansas_city,
mapTypeId: google.maps.MapTypeId.TERRAIN
};
map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
sector_callback(sector_data);
}
// Loop through the results array and place a marker for each
// set of coordinates.
window.sector_callback = function(results) {
var bounds = new google.maps.LatLngBounds();
for (var i = 0, len = results.features.length; i < len; i++) {
var coords = results.features[i].geometry.coordinates[0];
var path = [];
document.getElementById('coords').innerHTML += "Polygon "+i+"<br>";
for ( var j = 0; j < coords.length; j++ ){
// alert("coords["+j+"][1]="+coords[j][1]+", coords["+j+"][0]="+coords[j][0]);
var pt = new google.maps.LatLng(coords[j][1], coords[j][0])
bounds.extend(pt);
path.push(pt);
document.getElementById('coords').innerHTML += coords[j]+"<br>";
}
var polygons = new google.maps.Polygon({
path: path,
strokeColor: "#FF0000",
strokeOpacity: 0.8,
strokeWeight: 1,
fillColor: "#FF0000",
fillOpacity: 0.35,
map: map
});
}
map.fitBounds(bounds);
}
My own answer, for who need.
Data from js file:
var sector_data = {
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"properties":{"Name": "Bolivia","Description": "-","Color":"#ff9900"},
"geometry":{"type": "Polygon","coordinates":
[
[
[-58.159,-20.164], ... [-65.313,-10.253], ... [-58.159,-20.164]
]
]
}// close geometry
}// close pais
// using ","
,
{
"type": "Feature",
"properties":{"Name": "Cuba","Description": "-","Color":"#552233"},
"geometry":{"type": "Polygon","coordinates":
[
[
[-82.561,21.5716], ... , [-82.561,21.5716]
]
,
[
[-77.669,21.9519], ... , [-77.669,21.9519]
]
,
[
MORE POLYGONS
]
]
}// cierra geometry
}// cierra pais
// uso","
]
}; // END. NOTE YoU MUST DELETE '//' AND REST...
var map;
function initialize() {
var latinoamerica = new google.maps.LatLng(-5,-63);
var mapOptions = {
zoom: 10,
center: latinoamerica,
mapTypeId: google.maps.MapTypeId.HYBRID,
panControl: true,
panControlOptions: {
position: google.maps.ControlPosition.LEFT_TOP
},
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.LARGE,
position: google.maps.ControlPosition.LEFT_TOP
},
scaleControl: true,
streetViewControl: false,
};
map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
sector_callback(sector_data);
}
// Loop through the results array and place a marker for each
// set of coordinates.
window.sector_callback = function(results) {
var bounds = new google.maps.LatLngBounds();
for (var i = 0, len = results.features.length; i < len; i++) {
//console.log(i)
//document.getElementById('coords').innerHTML += "Polygon "+results.features[i].properties.Name+"<br>";
Color = results.features[i].properties.Color
cualpais = results.features[i].properties.Name
//console.log(nombre)
for (var a=0;a < results.features[i].geometry.coordinates.length; a++ ){
var coords = results.features[i].geometry.coordinates[a];
//console.log(a)
var path = [];
for ( var j = 0; j < coords.length; j++ ){
// alert("coords["+j+"][1]="+coords[j][1]+", coords["+j+"][0]="+coords[j][0]);
var nombre = new google.maps.LatLng(coords[j][1], coords[j][0])
bounds.extend(nombre);
path.push(nombre);
//document.getElementById('coords').innerHTML += coords[j]+"<br>";
}
var nombre = new google.maps.Polygon({
path: path,
strokeColor: "#f5f5f5",
strokeOpacity: 0.6,
strokeWeight: 1,
fillColor: Color,
fillOpacity: 0.35,
clickable: true,
//map: map
//console.log(map)
// console.log(nombre)
});
nombre.setMap(map);
}
map.fitBounds(bounds);
}}

How to open markers popups on leaflet via external link

Considering a custom floor plan been showed with leaflet with markers loaded from a geojson file. Each of the markers have a related page and those pages have hyperlinks aiming to the map. I would like to add #id to those hyperlinks.
If for example, the map url was domain.com/map, the "Marker 1" page (domain.com/marker-1) would have a link (domain.com/map#maker-1) that would open the map with the actual marker for "marker 1" on the center of the map with it's popup open.
My question is how do I open the map with a certain marker on the center and with it popups open when I add a hash to the url (domain.com/map#maker-1)?
Here goes my code:
index.php
<head>
<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.7.2/leaflet.js" />
<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.7.2/leaflet.css" />
<script src="geojson.js" type="text/javascript"></script>
</head>
<body>
<div id="map"></div>
<script src="map.js"></script>
</body>
geojson.js
var groupsGeoJson = {
"type": "FeatureCollection",
"features":[
{
"geometry": {
"type": "Point",
"coordinates": [-120,60]
},
"type": "Feature",
"properties": {
"popupContent": "<h1>Maker 1</h1>"
},
"id": 1
},
{
"geometry": {
"type": "Point",
"coordinates": [-80,40]
},
"type": "Feature",
"properties": {
"popupContent": "<h1>Maker 2</h1>"
},
"id": 2
}
]
};
map.js
var mapMinZoom = 2;
var mapMaxZoom = 6;
var mapIniZoom = 2;
var mapCenterLat = 20;
var mapCenterLng = -75;
var groupsIcon = L.icon({
iconUrl: 'images/silver_coin.gif',
iconSize: [32, 32],
iconAnchor: [16, 32],
popupAnchor: [0, -28]
});
var baseLayer = new L.TileLayer('layers/baseLayer/{z}/{x}/{y}.png', {
minZoom: mapMinZoom,
maxZoom: mapMaxZoom,
noWrap: true
});
var groups= L.geoJson(groupsGeoJson, {
pointToLayer: function (feature, latlng) {
return L.marker(latlng, {icon: groupsIcon});
}, onEachFeature: onEachFeature
});
var map = new L.Map('map', {
layers: [baseLayer, groups],
center: new L.LatLng(mapCenterLat, mapCenterLng),
zoom: mapIniZoom
});
var southWest = map.unproject([0, 16384], map.getMaxZoom());
var northEast = map.unproject([16384, 0], map.getMaxZoom());
var mapBounds = new L.LatLngBounds(southWest,northEast);
map.setMaxBounds(mapBounds);
function onEachFeature(feature, layer) {
var popupContent = "<p>Test</p>"
if (feature.properties && feature.properties.popupContent) {
popupContent += feature.properties.popupContent;
}
layer.bindPopup(popupContent);
}

Categories

Resources