Draw markers on leaflet map from geojson data - javascript

How to import geoJson data (with more than 2000 coordinates) into leaflet map?
This is short sample of geo json
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [ 44.8242557024,20.4048512901 ]
},
"properties": {
}
},
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [ 44.8242557024,20.4048512901 ]
},
"properties": {
}
},...]
Code I've tried:
<!doctype html>
<html>
<head>
<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.7.2/leaflet.css" />
<!--[if lte IE 8]>
<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.7.2/leaflet.ie.css" />
<![endif]-->
<style type="text/css">
body {
padding: 0;
margin: 0;
}
html, body, #cmap {
height: 100%;
}
</style>
<script src="http://cdn.leafletjs.com/leaflet-0.7.2/leaflet.js"></script>
<script src="http://code.jquery.com/jquery-2.1.0.min.js"></script>
</head>
<body>
<div id="cmap"></div>
<script>
var cupcakeTiles = L.tileLayer('https://api.mapbox.com/v4/mapbox.emerald/page.html?access_token=cj5h2mqa63sc92srx3bu62e2j', {
maxZoom: 18
});
$.getJSON("convertcsv.geojson", function(data) {
var geojson = L.geoJson(data, {
onEachFeature: function (feature, layer) {
layer.bindPopup(feature.properties.name);cj5h2mqa63sc92srx3bu62e2j
}
});
var map = L.map('map', {
center: [44, 20],
zoom: 7
});
L.tileLayer('https://{s}.tiles.mapbox.com/v3/{id}/{z}/{x}/{y}.png', {
id: 'examples.map-20v6611k'
}).addTo(map);
new L.GeoJSON(meta1nJson).addTo(map);
});
</script>
</body>
</html>
But nothing happens, it is just a gray background. I'm not sure where the mistake is (maybe there is more than one), but probably there is a mistake with importing geojson data and map token.
I'm total beginner at this. Thank in advance.

You seem to have to have many issues in your code. Firstly an element with id 'map' does not exist in your html, so the map layer cannot be placed. You have to add 'cmap' as the id in the below code.
var map = L.map('cmap', {
center: [44, 20],
zoom: 7
});
Also meta1nJson does not seem to be defined in your code, so the below code would not work.
new L.GeoJSON(meta1nJson).addTo(map);
The layer cupcakeTiles seems to be defined but is never added to the map. You also have a stray string in the below code which should be removed.
$.getJSON("convertcsv.geojson", function(data) {
var geojson = L.geoJson(data, {
onEachFeature: function (feature, layer) {
layer.bindPopup(feature.properties.name); //cj5h2mqa63sc92srx3bu62e2j
}
});

Related

How to visualize the geocode of an adress ? and in ideal situation knowing if this is inside my polygon?

I am doing a script for test if an adress is in an area, for exemple around a point. I use node.js for the server and then JavaScript with the API mapbox. I display the map with the polygon (the area), the central point and the search with autocomplete for adress.
But now I am wondering, how to have the geocode (lattitude and longitude) from the adress ?
I would like to take this coordinate for calculate if those coordinate are inside my polygon for example with one of those methods :
http://geomalgorithms.com/a03-_inclusion.html#wn_PinPolygon()
here my code :
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8' />
<title>Adress in/out area</title>
<meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />
<script src='https://api.tiles.mapbox.com/mapbox-gl-js/v1.3.1/mapbox-gl.js'></script>
<link href='https://api.tiles.mapbox.com/mapbox-gl-js/v1.3.1/mapbox-gl.css' rel='stylesheet' />
<style>
body { margin:0; padding:0; }
#map { position:absolute; top:0; bottom:0; width:100%; }
</style>
</head>
<body>
<script src='https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-geocoder/v4.4.1/mapbox-gl-geocoder.min.js'></script>
<link rel='stylesheet' href='https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-geocoder/v4.4.1/mapbox-gl-geocoder.css' type='text/css' />
<div id='map'> </div>
<script>
mapboxgl.accessToken = 'mytoken';
var map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/streets-v11',
center: [-73.943851,40.720021],
zoom: 13
});
var geocoder =new MapboxGeocoder({
accessToken: mapboxgl.accessToken,
mapboxgl: mapboxgl
});
map.addControl(geocoder);
geocoder.on('result', function(result) {
console.log(result);
});
map.on('load', function () {
map.addSource("checked-area", {
"type": "geojson",
"data": {
"type": "FeatureCollection",
"features": [{
"type": "Feature",
"geometry": {
"type": "Polygon",
"coordinates": [
[
[-73.9346845,40.7284786],
[-73.9382465,40.7281208 ],
[-73.9457138,40.7274053],
[-73.9517648,40.725454],
[-73.9560993,40.721486],
[-73.9564855,40.710394],
[-73.9406068,40.7118904],
[-73.9330966,40.713582],
[-73.9347274,40.7172251],
[-73.933955,40.7202501],
[-73.9351995,40.722722],
[-73.9282472,40.7243482],
[-73.9298351,40.727633],
[-73.9346845,40.7284786]
]
]
}
}, {
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [-73.943851,40.720021]
}
}]
}
});
map.addLayer({
"id": "area-boundary",
"type": "fill",
"source": "checked-area",
"paint": {
"fill-color": "#088",
"fill-opacity": 0.5
},
"filter": ["==", "$type", "Polygon"]
});
map.addLayer({
"id": "area-store",
"type": "circle",
"source": "checked-area",
"paint": {
"circle-radius": 6,
"circle-color": "#B42222"
},
"filter": ["==", "$type", "Point"],
});
});
</script>
</body>
</html>
this is more specially this part of code which deals with the search part for adress :
var geocoder =new MapboxGeocoder({
accessToken: mapboxgl.accessToken,
mapboxgl: mapboxgl
});
map.addControl(geocoder);
geocoder.on('result', function(result) {
console.log(result);
});
I would like from this code to take the coordinate to be able to calculate if they are inside the defined area (and in the future even without showing the map only with a message).
I tried with JSON.parse(result) and I have :
Uncaught SyntaxError: Unexpected token o in JSON
I also tried with result.geometry.coordinates and result['geometry']['coordinates']
If you have an idea you will help me a lot :)
PS: in case of minus please let me know why so that I could improve my post :)
Uncaught SyntaxError: Unexpected token o in JSON
This is mostly because you're trying to parse an object instead of JSON string. Have you tried accessing result.result.geometry instead. That gives the geometry.
geocoder.on("result", result => {
console.log(result.result.geometry);
});
You can also check if a point geometry lies within a polygon using turf.inside [1]
Here's a codepen: https://codepen.io/manishraj/full/bGbxOVG. Try searching for Pune, India and Delhi, India.
[1] https://github.com/Turfjs/turf-inside

Mapbox popup ReferenceError: features is not defined

I'm trying to display 3 fields properties from a geojson data that is loaded from a file. The data is loaded an added to the map. And the markers/points are display on the HTML page. BUt then I click on a marker/point nothing happens. Around .setLngLat(features.geometry.coordinates) I get an ReferenceError: features is not defined I'm not sure what I've missed or needed to do for it to be available to the current scope.
I would very much appreciate any hints or tips to resolve this.
{% load static %}
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'/>
<title></title>
<meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no'/>
<script src='https://api.tiles.mapbox.com/mapbox-gl-js/v0.37.0/mapbox-gl.js'></script>
<link href='https://api.tiles.mapbox.com/mapbox-gl-js/v0.37.0/mapbox-gl.css' rel='stylesheet'/>
<style>
body {
margin: 0;
padding: 0;
}
#map {
position: absolute;
top: 0;
bottom: 0;
width: 100%;
}
</style>
</head>
<body>
<div id='map'></div>
<script>
mapboxgl.accessToken = 'pk.myaccesstoken';
var map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/streets-v9',
center: [10.600, 55.900],
zoom: 6.0,
hash: true
});
map.on('load', function () {
// Add a layer showing the places.
map.addSource('markers', {
type: 'geojson',
data: '{% static 'json/architecture_map.geojson'%}'
});
map.addLayer({
"id": "places",
"source": "markers",
"type": "circle",
"paint": {
"circle-radius": 5,
"circle-color": "#fb05ff"
}
});
map.on('click', function (e) {
var f = map.queryRenderedFeatures(e.point, {layers: ['places']});
if (f.length) {
var feature = f[0];
new mapboxgl.Popup()
.setLngLat(features.geometry.coordinates)
.setHTML(ProjectPopup(feature))
.addTo(map);
}
});
function ProjectPopup(feature){
var html = '';
html += "<div>";
html += "<h2>" + feature.properties.project + "</h2>";
html += "<p>" + feature.properties.image + "</p>";
html += "<a>" + feature.properties.slug + "</a>";
html += "</div>";
return html;
}
// Change the cursor to a pointer when the mouse is over the places layer.
map.on('mouseenter', 'places', function () {
map.getCanvas().style.cursor = 'pointer';
});
// Change it back to a pointer when it leaves.
map.on('mouseleave', 'places', function () {
map.getCanvas().style.cursor = '';
});
});
</script>
</body>
</html>
Sample of the geojson file.
{
"type": "FeatureCollection",
"crs": {
"type": "name",
"properties": {
"name": "EPSG:4326"
}
},
"features": [
{
"type": "Feature",
"properties": {
"image": "project01.JPG",
"project": "Project Title",
"slug": "project-title"
},
"geometry": {
"type": "Point",
"coordinates": [
9.932241438432886,
57.04649628721196
]
}
}
]
}
First of all your provided geojson is not a valid one. You can check your geojson here: http://geojsonlint.com/
Second your "not defined" error might just be a typo. You defined your variable like this:
var feature = f[0];
But using is like this:
new mapboxgl.Popup()
.setLngLat(features.geometry.coordinates)
.setHTML(ProjectPopup(feature))
.addTo(map);
}
You notice that features is not the same as your defined variable named feature thus resulting in undefined.
I corrected your mistake. See here:
https://jsfiddle.net/andi_lo/xzrzzzsc

Google Maps API: getFeatureById for feature collection not working

I try to change the style of a specific feature of a feature collection data overlay. This is a snippet of my json:
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"id": 1,
"properties": {
"name": "1 CBD - Bankenviertel",
"color": "transparent",
"isHovered": false,
"isActive": false
},
"geometry": {
"type": "Polygon",
"coordinates": [
[
[
8.67279430349,
50.1143807311
],
[
8.67280054398,
50.1143975981
]
]
]
}
}
and this is the relevant snippet from my map.js
map.data.loadGeoJson('some.json');
console.log(map.data.getFeatureById(1));
And I am always getting "undefined" in the console.
What am I doing wrong here?
Thanks,
Robert
You need to call map.data.getFeatureById(1) inside the callback function (so it doesn't execute before the GeoJson has loaded).
from the documentation:
loadGeoJson(url:string, options?:Data.GeoJsonOptions, callback?:function(Array<Data.Feature>))
Return Value: None
Loads GeoJS
proof of concept fiddle
code snippet:
var geocoder;
var map;
function initialize() {
var map = new google.maps.Map(
document.getElementById("map_canvas"), {
zoom: 4,
center: {
lat: -28,
lng: 137
},
mapTypeId: google.maps.MapTypeId.ROADMAP
});
// map.data.addGeoJson(geoJson);
map.data.loadGeoJson(
'https://api.myjson.com/bins/1teyu', {},
function(features) {
console.log(map.data.getFeatureById(1));
console.log(map.data.getFeatureById(1).getProperty("letter"));
});
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="map_canvas"></div>

Google Maps JS API / GeoJSON import - infowindows not showing up when API Key is inserted

here is some code for a simple map that gets data from a geoJson variable. My problem is that the infowindows associated with markers won't show up. The strange thing is that if I remove the API Key script, everything seems to work correctly.
<!DOCTYPE html>
<html>
<head>
<title>Google Maps geoJson infowindow test</title>
<style type="text/css">
html, body, #map-canvas {
width: 100%;
height: 500px;
margin: 0px;
padding: 0px
}
</style>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3&sensor=false&libraries=drawing"></script>
<script type="text/javascript">
var map;
var marker;
var geocoder = new google.maps.Geocoder();
var infowindow = new google.maps.InfoWindow();
function initialize() {
// Create a simple map.
map = new google.maps.Map(document.getElementById('map-canvas'), {
zoom: 14,
center: new google.maps.LatLng(-27.779627,153.236112)
});
google.maps.event.addListener(map, 'click', function() {
infowindow.close();
});
// Load the associated GeoJSON
var data = {
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [153.236112, -27.779627]
},
"properties": {
"name": "[153.236112, -27.779627]",
"description": "Timestamp: 16:37:16.293"
}
},
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [153.230447, -27.777501]
},
"properties": {
"name": "[153.230447, -27.777501]",
"description": "Timestamp: 16:37:26.298"
}
}
]
}
map.data.addGeoJson(data)
// Set mouseover event for each feature.
map.data.addListener('click', function(event) {
infowindow.setContent(event.feature.getProperty('name')+"<br>"+event.feature.getProperty('description'));
infowindow.setPosition(event.latLng);
infowindow.setOptions({pixelOffset: new google.maps.Size(0,-34)});
infowindow.open(map);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="content"></div>
<table border="1">
<tr>
<td>
<div id="map-canvas" style="width:580px;height:620px;"></div>
</td>
<td valign="top" style="width:150px; text-decoration: underline; color: #4444ff;">
<div id="side_bar"></div>
</td>
</tr>
</table>
<div id="info"></div>
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=MY_SECRET_KEY&callback=initialize">
</script>
</body>
</html>
Code to remove to make it work locally:
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=MY_SECRET_KEY&callback=initialize">
</script>
Please need some advice. Thanks.
You are including the API twice, once with the drawing library and once with the callback function. Only include the API once, combine all the parameters (including your API key) as described in the documentation.
code snippet:
var map;
var marker;
var geocoder = new google.maps.Geocoder();
var infowindow = new google.maps.InfoWindow();
function initialize() {
// Create a simple map.
map = new google.maps.Map(document.getElementById('map-canvas'), {
zoom: 14,
center: new google.maps.LatLng(-27.779627, 153.236112)
});
google.maps.event.addListener(map, 'click', function() {
infowindow.close();
});
// Load the associated GeoJSON
var data = {
"type": "FeatureCollection",
"features": [{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [153.236112, -27.779627]
},
"properties": {
"name": "[153.236112, -27.779627]",
"description": "Timestamp: 16:37:16.293"
}
}, {
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [153.230447, -27.777501]
},
"properties": {
"name": "[153.230447, -27.777501]",
"description": "Timestamp: 16:37:26.298"
}
}]
}
map.data.addGeoJson(data)
// Set mouseover event for each feature.
map.data.addListener('click', function(event) {
infowindow.setContent(event.feature.getProperty('name') + "<br>" + event.feature.getProperty('description'));
infowindow.setPosition(event.latLng);
infowindow.setOptions({
pixelOffset: new google.maps.Size(0, -34)
});
infowindow.open(map);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map-canvas {
width: 100%;
height: 500px;
margin: 0px;
padding: 0px
}
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?callback=initialize&libraries=drawing"></script>
<div id="content"></div>
<table border="1">
<tr>
<td>
<div id="map-canvas" style="width:580px;height:620px;"></div>
</td>
<td valign="top" style="width:150px; text-decoration: underline; color: #4444ff;">
<div id="side_bar"></div>
</td>
</tr>
</table>
<div id="info"></div>

Loading geojson markers into mapbox setting custom icon image

I'm new to mapbox/leaflet and I think it's a pretty basic problem I'm fighting the last two days and though I've tried several ways I can't wrap my head around it.
I'm loading markers via geojson:
var ma_3 = L.mapbox.featureLayer().loadURL('./data/marathon/marker3x.geojson');
and then try to change properties like size or color according to the title used in the geojson data:
ma_3.on('ready', function(layer) {
this.eachLayer(function(marker) {
if (marker.toGeoJSON().properties.title === 'Verpflegung') {
marker.setIcon(L.mapbox.marker.icon({
"marker-size": 'large'
}));
} else {
marker.setIcon(L.mapbox.marker.icon({}));
}
marker.bindPopup(marker.toGeoJSON().properties.id + ', ' +
marker.toGeoJSON().properties.title);
});
})
.addTo(baseMap);
The geojson looks like this:
{
"type": "Feature",
"properties": {
"id": "marker-ie2tbbh05",
"title": "Verpflegung",
"description": "",
"marker-size": "medium",
"marker-color": "#b7ddf3",
"marker-symbol": "marker-stroked"
},
"geometry": {
"type": "Point",
"coordinates": [
6.431395,
51.19433
]
},
Am I missing something because I've also tried giving the marker a new face by using
var icon_live = L.icon({ iconUrl: './img/icon-live.png', iconSize: [35,35] });
somewhere in the setIcon function but nothing seems to work.
If someone could please point me in right direction. It's really appriciated.
I guess it's a typical beginners mistake and maybe it's just me but I found it pretty confusing in which context to use the several options of setIcon.
In the end I made it work using .on(layeradd) and marker.setIcon(pathToYourIcon).
ma_3.on('layeradd', function(layer) {
this.eachLayer(function(marker) {
if (marker.toGeoJSON().properties.title === 'Verpflegung') {
marker.setIcon(icon_live);
}
marker.bindPopup(marker.toGeoJSON().properties.id + ', ' +
marker.toGeoJSON().properties.title);
});
});
Have you seen this example yet?
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Custom marker icons</title>
<meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />
<script src='https://api.mapbox.com/mapbox.js/v2.2.2/mapbox.js'></script>
<link href='https://api.mapbox.com/mapbox.js/v2.2.2/mapbox.css' rel='stylesheet' />
<style>
body { margin:0; padding:0; }
#map { position:absolute; top:0; bottom:0; width:100%; }
</style>
</head>
<body>
<div id='map'></div>
<script>
L.mapbox.accessToken = '<your access token here>';
var map = L.mapbox.map('map', 'mapbox.streets')
.setView([40, -74.50], 8);
var myLayer = L.mapbox.featureLayer().addTo(map);
var geoJson = [{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [-75.00, 40]
},
"properties": {
"title": "Small astronaut",
"icon": {
"iconUrl": "/mapbox.js/assets/images/astronaut1.png",
"iconSize": [50, 50], // size of the icon
"iconAnchor": [25, 25], // point of the icon which will correspond to marker's location
"popupAnchor": [0, -25], // point from which the popup should open relative to the iconAnchor
"className": "dot"
}
}
}, {
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [-74.00, 40]
},
"properties": {
"title": "Big astronaut",
"icon": {
"iconUrl": "/mapbox.js/assets/images/astronaut2.png",
"iconSize": [100, 100],
"iconAnchor": [50, 50],
"popupAnchor": [0, -55],
"className": "dot"
}
}
}];
// Set a custom icon on each marker based on feature properties.
myLayer.on('layeradd', function(e) {
var marker = e.layer,
feature = marker.feature;
marker.setIcon(L.icon(feature.properties.icon));
});
// Add features to the map.
myLayer.setGeoJSON(geoJson);
</script>
</body>
</html>
*Source: https://www.mapbox.com/mapbox.js/example/v1.0.0/custom-marker/

Categories

Resources