Loading geojson markers into mapbox setting custom icon image - javascript

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/

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

Draw markers on leaflet map from geojson data

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

Leaflet does not mark point with geojsonFeatures?

I'm starting on Leaflet API and I hope to add some geometry points to a customer map using GeoJson data. Currently, I used the geojsonFeaturetype present here http://leafletjs.com/examples/quick-start.html
But, when I follow such steps to add the features, the ones does not appears. Below is my html page and code.
<html><head>
<title>Leaflet Quick Start Guide Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet/v0.7.7/leaflet.css">
</head>
<body class="">
<div id="mapid" style="width: 600px; height: 400px; position: relative;" class="leaflet-container leaflet-fade-anim" tabindex="0"></div>
<script src="http://cdn.leafletjs.com/leaflet/v0.7.7/leaflet.js"></script>
<script src="https://raw.github.com/calvinmetcalf/leaflet-ajax/master/dist/leaflet.ajax.min.js"></script>
<script>
var mymap = L.map('mapid').setView([51.505, -0.09], 13);
L.tileLayer('https://api.mapbox.com/styles/v1/edsonbarboza/ciqb82pfe000dc1nliqy8sljp/tiles/256/{z}/{x}/{y}?access_token=pk.eyJ1IjoiZWRzb25iYXJib3phIiwiYSI6ImNpbTJjMWRuczA5NGx1MGtzbmN6c3NjOHMifQ.FvAMXzmnQ0TIJDDsV6rXAw', {
maxZoom: 18,
attribution: 'Map data © OpenStreetMap contributors, ' +
'CC-BY-SA, ' +
'Imagery © Mapbox',
id: 'mapbox.satelity'
}).addTo(mymap);
var myStyle = {
"color": "#ff7800",
"weight": 5,
"opacity": 0.65
};
//L.marker([51.51, -0.09]).addTo(mymap)
var geojsonFeature = {
"type": "Feature",
"properties": {
"name": "Coors Field",
"amenity": "Baseball Stadium",
"popupContent": "This is where the Rockies play!"
},
"geometry": {
"type": "Point",
"coordinates": [51.51, -0.09]
}
};
var myLayer = L.geoJson().addTo(mymap);
myLayer.addData(geojsonFeature);
<!-- var geojsonLayer = new L.GeoJSON.AJAX("geojson_data.json", {style:myStyle}); -->
<!-- geojsonLayer.addTo(mymap); -->
var popup = L.popup();
function onMapClick(e) {
popup
.setLatLng(e.latlng)
.setContent("You clicked the map at " + e.latlng.toString())
.openOn(mymap);
}
mymap.on('click', onMapClick);
</script>
Thanks for any help.
You must invert the coordinates in the geometry.
var geojsonFeature = {
"type": "Feature",
"properties": {
"name": "Coors Field",
"amenity": "Baseball Stadium",
"popupContent": "This is where the Rockies play!"
},
"geometry": {
"type": "Point",
"coordinates": [-0.09, 51.51]
}
};
Here is your sample with correction
This is specified here

How can I display multiple MapBox maps on a Squarespace page?

I want to show 2 Mapbox maps side to side on the same page.
The SF map works as advertised (popup on hover), but the NY map does not show its markers. What am I doing wrong?
Thanks much!
Here is the page with a NY and a SF map: link.
In that page header I injected:
<script src='https://api.mapbox.com/mapbox-gl-js/v0.20.0/mapbox-gl.js'></script>
<link href='https://api.mapbox.com/mapbox-gl-js/v0.20.0/mapbox-gl.css' rel='stylesheet' />
The NY map code block:
<style>
.mapboxgl-popup {
max-width: 400px;
letter-spacing: 1px;
font: 16px/20px 'Helvetica Neue', Arial, Helvetica, sans-serif;
}
.marker-title {
font-weight: 300;
}
</style>
<div id='mapny' style='width: 100%; height: 400px;'></div>
<script>
mapboxgl.accessToken = 'pk.eyJ1IjoibWFwYm94Y29vcmRpbmF0ZXMiLCJhIjoiY2lwOGhicDN3MDE5dXQ2bHk5Mmw0MGQ3YiJ9.ilUY49cMzmQGR6VKfz95CA';
var markers = {
"type": "FeatureCollection",
"features": [{
"type": "Feature",
"properties": {
"description": "<div class=\"marker-title\">Skylight at Moynihan Station</div>",
"marker-symbol": "marker"
},
"geometry": {
"type": "Point",
"coordinates": [-73.99557 , 40.75176]
}
}, {
"type": "Feature",
"properties": {
"description": "<div class=\"marker-title\">Skylight One Hanson</div>",
"marker-symbol": "marker"
},
"geometry": {
"type": "Point",
"coordinates": [-73.97791 , 40.68511]
}
}, {
"type": "Feature",
"properties": {
"description": "<div class=\"marker-title\">Skylight Clarkson SQ</div>",
"marker-symbol": "marker"
},
"geometry": {
"type": "Point",
"coordinates": [-74.00956, 40.72825]
}
}, {
"type": "Feature",
"properties": {
"description": "<div class=\"marker-title\">Skylight Modern</div>",
"marker-symbol": "marker"
},
"geometry": {
"type": "Point",
"coordinates": [-74.00401 , 40.7511 ]
}
}]
};
var map = new mapboxgl.Map({
container: 'mapny',
style: 'mapbox://styles/mapboxcoordinates/cipfsc92i000bbkmbypwkvi1c',
center: [-73.993235, 40.712980],
pitch: 60,
zoom: 11.5
});
map.on('load', function () {
// Add marker data as a new GeoJSON source.
map.addSource("markers", {
"type": "geojson",
"data": markers
});
// Add a layer showing the markers.
map.addLayer({
"id": "markers",
"type": "symbol",
"source": "markers",
"layout": {
"icon-image": "{marker-symbol}-15",
"icon-allow-overlap": true
}
});
});
// Create a popup, but don't add it to the map yet.
var popup = new mapboxgl.Popup({
closeButton: false,
closeOnClick: false
});
map.on('mousemove', function(e) {
var features = map.queryRenderedFeatures(e.point, { layers: ['markers'] });
// Change the cursor style as a UI indicator.
map.getCanvas().style.cursor = (features.length) ? 'pointer' : '';
if (!features.length) {
popup.remove();
return;
}
var feature = features[0];
// Populate the popup and set its coordinates
// based on the feature found.
popup.setLngLat(feature.geometry.coordinates)
.setHTML(feature.properties.description)
.addTo(map);
});
</script>
The SF map code block:
<style>
.mapboxgl-popup {
max-width: 400px;
letter-spacing: 1px;
font: 16px/20px 'Helvetica Neue', Arial, Helvetica, sans-serif;
}
.marker-title {
font-weight: 300;
}
</style>
<div id='mapsf' style='width: 100%; height: 400px;'></div>
<script>
mapboxgl.accessToken = 'pk.eyJ1IjoibWFwYm94Y29vcmRpbmF0ZXMiLCJhIjoiY2lwOGhicDN3MDE5dXQ2bHk5Mmw0MGQ3YiJ9.ilUY49cMzmQGR6VKfz95CA';
var markers = {
"type": "FeatureCollection",
"features": [{
"type": "Feature",
"properties": {
"description": "<div class=\"marker-title\">Skylight at Pier 38</div>",
"marker-symbol": "marker"
},
"geometry": {
"type": "Point",
"coordinates": [ -122.38769, 37.78257]
}
}, {
"type": "Feature",
"properties": {
"description": "<div class=\"marker-title\">Skylight at the Mint</div>",
"marker-symbol": "marker"
},
"geometry": {
"type": "Point",
"coordinates": [ -122.40725, 37.78272]
}
}]
};
var map = new mapboxgl.Map({
container: 'mapsf',
style: 'mapbox://styles/mapboxcoordinates/cipfsc92i000bbkmbypwkvi1c',
center: [-122.409898, 37.775668],
pitch: 60,
zoom: 12
});
map.on('load', function () {
// Add marker data as a new GeoJSON source.
map.addSource("markers", {
"type": "geojson",
"data": markers
});
// Add a layer showing the markers.
map.addLayer({
"id": "markers",
"type": "symbol",
"source": "markers",
"layout": {
"icon-image": "{marker-symbol}-15",
"icon-allow-overlap": true
}
});
});
// Create a popup, but don't add it to the map yet.
var popup = new mapboxgl.Popup({
closeButton: false,
closeOnClick: false
});
map.on('mousemove', function(e) {
var features = map.queryRenderedFeatures(e.point, { layers: ['markers'] });
// Change the cursor style as a UI indicator.
map.getCanvas().style.cursor = (features.length) ? 'pointer' : '';
if (!features.length) {
popup.remove();
return;
}
var feature = features[0];
// Populate the popup and set its coordinates
// based on the feature found.
popup.setLngLat(feature.geometry.coordinates)
.setHTML(feature.properties.description)
.addTo(map);
});
</script>

Openlayers 3 : popup by geojson file

How do you put GeoJSON attribute information in a popup with OpenLayers 3
I need to display the informations included in my geojson file into the popup. Here is my method but it gives me undefined.
My GeoJson file:
{ "type": "FeatureCollection", "features": [{ "type": "Feature", "properties": { "name": "Caen - Campus 3 "}, "geometry": { "type": "Point", "coordinates": [-0.353538,49.148791] } }, { "type": "Feature", "properties": { "name": "Caen "}, "geometry": { "type": "Point", "coordinates": [-0.369770,49.184403] } }
Here is my method
var element = document.getElementById('popup');
var popup = new ol.Overlay({
element: element
});
map.addOverlay(popup)
map.on('click', function(evt){
var feature = map.forEachFeatureAtPixel(evt.pixel,
function(feature, layer) {
return feature;
});
if ( feature ) {
var geometry = feature.getGeometry();
var coord = geometry.getCoordinates();
var nom = feature.getProperties();
//var nam = nom.type;
popup.setPosition(coord);
$(element).popover({
'placement': 'top',
'html': true,
'content': '<p>'+feature.get('name')+'</p>'
});
$(element).popover('show');
} else {
$(element).popover('destroy');
}
});
I create the popup when I click on it displays me 'undefined'. I think that don't use the good method to put the 'name' object included on the GeoJson file: feature.get('name')
I think that I don't uses the best method. Thank for your help.

Categories

Resources