TurfJS Add Point to MapBox Map - javascript

New to Turf JS and have been looking at integration via the MapBox API. Using the default MapBox.Outdoors map and have been following some of the example TurfJS documentation http://turfjs.org/docs/#point but can't seem to get my point plotting on top of the map. Any suggestions greatly appreciated, the error seems to be in my list line of code in relation to the FeatureLayer.setGeoJSON but I can't figure it out. If I leave the last line active the map doesn't load, if I comment it out the map loads but no pin shows up?
<BODY>
<div id='map'></div>
<script>
L.mapbox.accessToken = 'pk.eyJ1IjoibWFya2d1ayIsImEiOiJjaXNsd2VhMG8wMDdrMzNybmticDJhdnZsIn0.KXcvejg6QplSsAlj8aimjA';
var point = turf.point([35.463453, -97.514914], {
"title": "OKC Thunder",
"description": "100 W Reno Ave, Oklahoma City",
"marker-color": "#6BC65F",
"marker-size": "large",
"marker-symbol": "basketball"
});
var map = L.mapbox.map('map', 'mapbox.outdoors').setView([35.463453, -97.514914], 19);
.featureLayer.setGeoJSON(point); // If I comment this line out the map loads with no pin. If I leave this line active the map doesn't load at all?
</SCRIPT>
</BODY>

I think the problem is that you're trying to add geojson to the map without converting it first. You need to convert the geojson to a format that leaflet can use. Here is an example that should work for you. It will also bind a popup to the point marker that will display the properties for you. The style part can be done either statically (like for all properties except title) so that it would be applied to all points within the feature collection, or dynamically using each features properties (as is done with title).
var map = L.mapbox.map('map', 'mapbox.outdoors').setView([35.463453, -97.514914], 19);
var featureCollection = {"type": "FeatureCollection", "features": [{"type": "Feature", "properties": {"title": "OKC Thunder"}, "geometry": {"type": "Point", "coordinates": [35.463453, -97.514914]}}]};
L.geoJson(featureCollection, {
onEachFeature: function (feature, layer) {
layer.bindPopup(""+feature.properties+"<br />");
},
style: function (feature) {
style = {
"title": feature.properties.title,
"description": "100 W Reno Ave, Oklahoma City",
"marker-color": "#6BC65F",
"marker-size": "large",
"marker-symbol": "basketball"
};
return style
}
}).addTo(map)

I think you should use the set marker function that mapbox makes available to you. So you can skip creating a feature layer and just use the mapbox-marker function. It is documented here:
https://www.mapbox.com/mapbox.js/api/v3.0.1/l-marker/
There is also a description of how to create a simple marker here:
https://www.mapbox.com/mapbox.js/example/v1.0.0/l-mapbox-marker/
For the code you provided you could just skip the creation of a geojson object via turf.point and just use this:
var map = L.mapbox.map('map', 'mapbox.outdoors').setView([-97.514914, 35.463453, ], 19);
L.marker([-97.514914, 35.463453], {
icon: L.mapbox.marker.icon({
"title": "OKC Thunder",
"description": "100 W Reno Ave, Oklahoma City",
"marker-color": "#6BC65F",
"marker-size": "large",
"marker-symbol": "basketball"
})
}).addTo(map);
Or if you want to use geojson with turf.point you could also do it that way:
var point = turf.point([-97.514914, 35.463453], {
"title": "OKC Thunder",
"description": "100 W Reno Ave, Oklahoma City",
"marker-color": "#6BC65F",
"marker-size": "large",
"marker-symbol": "basketball"
});
var coords = point.geometry.coordinates;
var map = L.mapbox.map('map', 'mapbox.outdoors').setView([-97.514914, 35.463453, ], 19);
L.marker(coords, {
icon: L.mapbox.marker.icon(point.properties)
}).addTo(map);
Also make sure that you need to flip your point coordinates from
[35.463453, -97.514914] to [-97.514914, 35.463453] to match the geojson specification which is "projected coordinates, longitude, latitude for geographic coordinates"
http://geojson.org/geojson-spec.html#id2

Related

How to use a geojson file with javascript in order to create polygones with leaflet?

I am trying to create a map with the limitations of the departments as polygons with leaflet. I have the geojson file on my computer. For that, I intend to use the polygon function of leaflet as follows;
var polygon = L.polygon(departementsmetropole.geojson).addTo(map);
</script>
As you can see, I don't know how to use it. My goal is to extract the coordinates of the files in order to put them in the function. The file being the fronteers of the departments, I can't add them manually because each department has around 5000 points of coordinates.
I am a beginner so, as you can see above, I tried to put the file directly where it should go by the coordinates, but it didn't work. I also tried to use the get method without success.
In official documentation you will get all necessary.
In addition, you have the following jsfiddle example https://jsfiddle.net/ToniBCN/8nft2yhm/
// center of the map
var center = [55.8, -4.2];
// Create the map
var map = L.map('map').setView(center, 3);
// a GeoJSON multipolygon
var mp = {
"type": "Feature",
"geometry": {
"type": "Polygon",
"coordinates": [
[
[-3.9, 56],
[-3.9, 55.6],
[-4.6, 55.6],
[-4.6, 56],
[-3.9, 56]
],
[
[-4.42136131224148, 55.9201880414654],
[-4.44608055051929, 55.8994054388937],
[-4.49963890012121, 55.8816929539651],
[-4.44196067747298, 55.8362196009829],
[-4.35269676146979, 55.8045881227693],
[-4.35818992553152, 55.7636605341908],
[-4.22772727906531, 55.7350629547249],
[-4.07391868533672, 55.7582517890959],
[-4.00937400761133, 55.7984131283508],
[-4.04095970096631, 55.868595920571],
[-4.14532981813928, 55.8947855700627],
[-4.27991233765179, 55.9148010288061],
[-4.29776512085243, 55.9586449375958],
[-4.42136131224148, 55.9201880414654]
]
]
},
"properties": {
"name": "MultiPolygon",
"style": {
color: "orange",
opacity: 1,
fillColor: "gray",
fillOpacity: 0.3
}
}
};
var mp2 = {
"type": "Feature",
"geometry": {
"type": "Polygon",
"coordinates": [
[
[-4.42136131224148, 55.9201880414654],
[-4.44608055051929, 55.8994054388937],
[-4.49963890012121, 55.8816929539651],
[-4.44196067747298, 55.8362196009829],
[-4.35269676146979, 55.8045881227693],
[-4.35818992553152, 55.7636605341908],
[-4.22772727906531, 55.7350629547249],
[-4.07391868533672, 55.7582517890959],
[-4.00937400761133, 55.7984131283508],
[-4.04095970096631, 55.868595920571],
[-4.14532981813928, 55.8947855700627],
[-4.27991233765179, 55.9148010288061],
[-4.29776512085243, 55.9586449375958],
[-4.42136131224148, 55.9201880414654]
]
]
},
"properties": {
"name": "MultiPolygon2",
"style": {
color: "red",
opacity: 1,
fillColor: "green",
fillOpacity: 0.3
}
}
};
new L.GeoJSON(mp, {
style: function(feature) {
return feature.properties.style
}
}).addTo(map);
new L.GeoJSON(mp2, {
style: function(feature) {
return feature.properties.style
}
}).addTo(map);
// Set up the OSM layer
L.tileLayer(
'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
maxZoom: 18
}).addTo(map);

Google Maps - addGeoJson is not working for my file

addGeoJson is not working in google map for my file
please check below code that I am using in javascript
//create the map
map = new google.maps.Map(document.getElementById('map-canvas'), {
zoom: 6,
center: {lat:49.79, lng: -8.82}
});
// Load GeoJSON.
var promise = $.getJSON("Sensitive_Areas_Nitrates_Rivers.json"); //same as map.data.loadGeoJson();
promise.then(function(data){
cachedGeoJson = data; //save the geojson in case we want to update its values
console.log(cachedGeoJson);
map.data.addGeoJson(cachedGeoJson,{idPropertyName:"id"});
});
I have downloaded this file from here
you can check my JSON file
Sensitive_Areas_Nitrates_Rivers.json
also, you can check this link with polygon
I have used below JSON format so you can check it
{
"type": "FeatureCollection",
"crs": {
"type": "name",
"properties": {
"name": "EPSG:27700"
}
},
"features": [
{
"type": "Feature",
"id": 1,
"geometry": {
"type": "MultiLineString",
"coordinates": [
[
[
500051.6875,
224280.03130000085
],
[
500047.2812999999,
224277.6875
],
[
499977.5937999999,
224242.625
],
[
499976.6875,
224242.21880000085
]
]
]
},
"properties": {
"OBJECTID": 8,
"type_of_sa": "SA_N",
"datedesign": 1025136000000,
"name": "Rivers Itchen",
"length_km": 12,
"uwwtd_code": "UKENRI134",
"shape_Length": 12172.080443901654
}
}
]
}
[500051.6875, 224280.03130000085] - [X, Y] coordinates may be in EPSG: 27700 to EPSG:4326, Now we need to display these coordinates on google map, Is there any solution for this?
Since Google Maps expects GeoJSON to be in EPSG:4326, Sensitive_Areas_Nitrates_Rivers.json needs to be reprojected. QGIS, for instance, could be utilized for that matter (refer docs for a details)
Reprojected Sensitive_Areas_Nitrates_Rivers.json layer will be displayed like this:
You are getting coordinates in metres. For displaying in google map you need to convert it into [Lng, Lat].
For converting metres to [Lng, Lat] you need to change the projection from EPSG: 27700 to 4326
then only you are able to get this geojson in [Lng, Lat]
Tool you can use: QGIS Desktop 3.4.14
Link: https://qgis.org/en/site/forusers/download.html
After convert you need to export this file as feature.

Multiple waypoints in leaflet js

This is my code to create multiple waypoints.
I have an array with 'n' number of lattitude and longitude i want the route based on that lat,long.I don't want to use any hardcore data's in waypoints.
In waypoints array i want to use dynamic lattitude and longitude,how to use this?
var data = [
{
"title": 'Chennai',
"lat": '13.0827',
"lng": '80.2707',
"description": '',
"flag":'1'
}
,
{
"title": 'Ramapuram',
"lat": '13.0317',
"lng": '80.1817',
"description": ''
}
,
{
"title": 'Kanchipuram',
"lat": '12.8342',
"lng": '79.7036',
"description": '',
"flag":'1'
},
];
var map = L.map('map');
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap contributors'
}).addTo(map);
var routeControl = L.Routing.control({
}).addTo(map);
routeControl.setWaypoints(data);
Here i have attached the image and this is my output,and also my expectation is i want to remove the center marker.i want to set the marker where i want.
Can anyone help me out?Now i have updated my code that i removed waypoints and i set the waypoints using setwaypoints function.Now i wantto remove the markers.
If I understand correctly, you want to draw a route along some waypoints and show markers only for start and end points. Also you want to prevent users from adding new waypoints. Create control like that:
L.Routing.control({
waypoints: yourWaypoints,
plan: L.Routing.plan(yourWaypoints, {
createMarker: function(i, wp, n) {
if (i == 0 || i == n - 1) {
return L.marker(wp.latlng, {
draggable: false // prevent users from changing waypoint position
});
} else {
return false;
}
}
},
addWaypoints: false // prevent users from adding new waypoints
});

How to convert zip code into GeoJSON

I have an array of users containing their zip codes and i would like to display their location based on their zipcode on Google Maps but i cannot turn my zipcode into a GeoJSON format. Help me
From what I looked up GeoJSON uses latitude and longitude right?
If that's the case you can just use another api that tells you latitude and longitude based on the zip code you input in its query.
Using google api:
http://maps.googleapis.com/maps/api/geocode/json?address={zipcode}
extract the lat/lon coordinate values from the JSON above:
var zipCode; //from your array of users
$.getJSON("http://maps.googleapis.com/maps/api/geocode/json?address=" + zipCode, function (json){
var latitude = json.results[0].geometry.location.lat;
var longitude = json.results[0].geometry.location.lng;
//Handle your geoJSON here, I'm just guessing on this part I don't know geoJSON
var geojsonFeature =
{
"type": "Feature",
"properties":
{
"name": "",
"amenity": "",
"popupContent": ""
},
"geometry":
{
"type": "Point",
"coordinates": [latitude, longitude]
}
};
L.geoJSON(geojsonFeature).addTo(map);
});

Javascript dynamically create image/icon (marker) from data

I want to display a map (Google maps initially) in a website (e.g. the position of some runners in an event/race), alongisde some markers with the initials of each runner. That is, depending on the data I get in JSON format:
data = [
{
"lat": 44.363,
"lng": 3.044,
"full_name": "Paul Cardiff"
}
{
"lat": 44.473,
"lng": 3.144,
"full_name": "Mark Zein"
}
...
]
I would like to represent the current position of each runner in the map with a marker identified by its initials (Mark Zein --> M.Z.). For instance (forgive me for this representation):
-----
|M.Z| _______________________road
----- --|-- /
|P.C| _________v________|
--|-- /
___v__________/
I know I can create a google.maps.Marker with a custom icon, but I am finding hard to create these icons dinamically based on data I receive (and that might change over time).
Is there a way to dynamically create images/icons from data? Or can you think of another way of generating these icons?
I've been doing some research but so far I didn't find something, so any help will be much appreciated!
Edited:
I am currently mocking the way I get the data, but the idea is to get the data from a socket. So what I have in my code right now is:
var json_socket = {
"lat": 44.363,
"lng": 3.044,
"full_name": "Paul Cardiff"
};
And how I add the markers:
var live_user = {lat: json_socket["lat"], lng: json_socket["lng"]};
var marker = new google.maps.Marker({
position: live_user,
map: map,
icon: "icon.png"
});
You can iterate over the array of markers with simple loop
I used the label to display the initials
var data = [{
"lat": 44.363,
"lng": 3.044,
"full_name": "Paul Cardiff"
} {
"lat": 44.473,
"lng": 3.144,
"full_name": "Mark Zein"
}
...
];
for (var i = 0; i < data.length; i++) {
var item = data[i];
var latLng = new google.maps.LatLng(item.lat, item.lng);
var initials = item.full_name.match(/\b(\w)/g).join('');
// Creating a marker and putting it on the map
var marker = new google.maps.Marker({
position: latLng,
map: map,
label: initials,
icon: "icon.png"
});
}

Categories