Drawing boundaries on a map with LeafletJS - javascript

I'm starting to play with code that can generate maps. I am now looking at OSM (OpenStreetMaps) as a great solution. Also LeafletJS makes it very easy to draw maps based on OSM. So far so good.
I would like to be able to draw an outline (boundary) of a county and am trying to understand how this process will look like. Do I first make a call to find coords and then pass them into Leaflet or is there a better way?
I can get boundaries using Nominatim API, but calling like this:
https://nominatim.openstreetmap.org/ui/search.html?state=tx&county=Lee
And I can draw area in Leaflet like this:
var polygon = L.polygon([
[51.509, -0.08],
[51.503, -0.06],
[51.51, -0.047]
]).addTo(mymap);
So, am I overthinking or this is how it works?

You can create a single function to get the county geometry and add it to map. Try the following code:
function drawCountyBoundary(county, state)
{
url = `https://nominatim.openstreetmap.org/search.php?county=${county}&state=${state}&polygon_geojson=1&format=jsonv2`
fetch(url).then(function(response) {
return response.json();
})
.then(function(json) {
geojsonFeature = json[0].geojson;
L.geoJSON(geojsonFeature).addTo(map);
});
}
drawCountyBoundary('Lee', 'Tx')

Related

How to the Leaflet CoordsToLatLngs to draw a polyline onto a map?

I have a geoJson file with an array of coordinates that I am trying to make into a polyline on a map using leaflet.
My code worked initially but I then realised that the longitude and latitudes are reversed in my geoJson file, so this was taking me to different coordinates.
I tried to reverse these using the coordsToLatLngs() method but keeping getting an error that this method isn't defined as it's static:
Uncaught ReferenceError: coordsToLatLngs is not defined
[This is a link to the leaflet documentation on this section] 1https://leafletjs.com/reference-0.7.7.html#geojson
Any guidance as to how I can use this method so that I can switch the long and lat around?
My code for this section:
var latLngCoords = coordsToLatLngs(value.coords, 0, false);
var polyline = L.polyline(latLngCoords, {color: 'red'}).addTo(mymap);
mymap.fitBounds(polyline.getBounds());
```
coordsToLatLngs is not imported to global scope
try to run like this
L.coordsToLatLngs(value.coords, 0, false)
or
L.GeoJSON.coordsToLatLngs(value.coords, 0, false)
or, there is turf.js library https://turfjs.org/docs/#flip with flip function
let coords = turf.lineString(latLngCoords)
let newCoords = turf.flip(coords)

Get Lat Lng when drawing a polygon with Google Maps drawing tool

I got the Google Map and Drawing Tools displayed on the map. I can draw the shapes (circle, polygon, rectangle ...) on the map. For the start I am using the example code from Google Maps JavaScript get started page: https://developers-dot-devsite-v2-prod.appspot.com/maps/documentation/javascript/examples/drawing-tools
I was able to find a lot of examples on have to draw/make a shape object by providing all the properties and LatLng.
How do I get a LatLng for the shape that I just draw by using one of the drawing tools form Drawing Tools toolbar?
I am planing to make an application which will allow user to draw shapes on the map and save the LatLng in to database (i will be using MySql), so later the shape can be displayed again on the map as per request.
Please help.
There are a few ways to get the coordinates of the shapes you draw on the map. Specifically for polygons you can add an event listener to the map like so. The easiest way is to add an event listener to the map for when a polygon is finished drawing.
google.maps.event.addListener(drawingManager, 'polygoncomplete', function(polygon) {
const coords = polygon.getPath().getArray().map(coord => {
return {
lat: coord.lat(),
lng: coord.lng()
}
});
console.log(JSON.stringify(coords, null, 1));
// SAVE COORDINATES HERE
});
Each type of drawing has a different format for saving so for something like circles you'd do
google.maps.event.addListener(drawingManager, 'circlecomplete', function(circle) {
const radius = circle.getRadius();
// Save circle here
});
You also have the option of adding an event to listen for all of the events by listening to the overlaycomplete event but in that case you'd have to handle the different types inside the event.
google.maps.event.addListener(drawingManager, 'overlaycomplete', function(event) {
if (event.type == 'circle') {
// Handle Circle using event.overlay
}
if (event.type == 'polygon') {
// Handle Polygon using event.overlay
}
});
Here's an example:
https://jsfiddle.net/juop8q3n/1/
And here's my sources:
https://developers-dot-devsite-v2-prod.appspot.com/maps/documentation/javascript/drawinglayer#drawing_events
https://developers-dot-devsite-v2-prod.appspot.com/maps/documentation/javascript/reference#drawing-on-the-map
EDIT
Another way I've seen people save the data is by adding an event listener to the map to get the GeoJSON data, which is a standard format for saving drawing data.
Link: http://jsfiddle.net/y89rbfLo/

Check if a point is inside polygon in OpenLayers 3

When I draw a polygon in an OpenLayers map, I want to know if the marker is inside the polygon or not. I searched in the OpenLayers API, but didn't find a solution.
And you can see my full code in this link.
I have the impression that I have to modify this function:
function addInteraction() {
var value = typeSelect.value;
if (value !== 'None') {
draw = new ol.interaction.Draw({
source: vectorSource,
type: /** #type {ol.geom.GeometryType} */ (typeSelect.value)
});
map.addInteraction(draw);
draw.on('drawend',function(e){
//Here
});
}
}
How can I do this?
You have a method 'intersectsCoordinate' for the ol.geom.Geometry.
So the code for that will look like:
var polygonGeometry = e.feature.getGeometry();
var coords = iconFeature.getGeometry().getCoordinates();
polygonGeometry.intersectsCoordinate(coords)
You can use the JSTS library, which implements simple geometry processing such as intersects, difference, etc. It contains an OL3 parser that allows the conversion of geometry from OL3 to JSTS and vice-versa.
See an example in OL3. Basically, you would use a process that checks if the geometry of your marker is within your polygon or not and do what you want from there.

How to make Mapbox maps (with directions.js) read only? - (and prevent users from moving markers)

My maps with walking directions in Mapbox are not read only. Users can move the markers' original locations.
I referred to layer options
https://github.com/mapbox/mapbox-directions.js/blob/mb-pages/API.md#layer-options
And added:
var Layer = L.LayerGroup.extend({
options: {
readonly: true
}
});
The map remains interactive and users can move markers around.
Any suggestions?
Fiddle: https://jsfiddle.net/q9grgbt0/
You're adding the options to something called Layer, but you never use Layer. You should be adding it to directionsLayer instead. It should look something like this:
var directionsLayer = L.mapbox.directions.layer(directions, {readonly: true}).addTo(map);
I've updated your fiddle with this code fix. I also cleaned up some of the code and got rid of the unnecessary variable Layer.

Plot Centroid of Feature Layer Polygon

Here is the rest service I'm working from:
http://sampleserver6.arcgisonline.com/arcgis/rest/services/Census/MapServer/3
My current call for displaying the feature layer is as follows:
var recLayer = new FeatureLayer("http://sampleserver6.arcgisonline.com/arcgis/rest/services/Census/MapServer/3",{
infoTemplate: recParkTemplate,
outFields: ["STATE_NAME"]
});
map.addLayer(recLayer);
However, instead of plotting the polygon on the map as this is an esriGeometricPolygon. I would rather have it plot on the map like a esriGeometryPoint. I know this method in getting the specific polygon's centroid:
https://developers.arcgis.com/javascript/jsapi/polygon-amd.html#getcentroid
My problem is I can't figure out how to cycle among all polygons in the feature layer and then plot those polygons. I can only point and click and display similar to how this ESRI sample works: https://developers.arcgis.com/javascript/jssamples/util_label_point.html
Thank you for your assistance.
Here is the current site if you would like to take a look at it: http://joshferrell.net/ece_project/
to cycle among all geometries in your feature layer you can do something like this:
recLayer.on("update-end", function changeHandler(evt) {
require(["dojo/_base/array"], function (array) {
array.forEach(recLayer.graphics, function (entry, i) {
console.debug(entry, "at index", i);
});
});
});
inside the loop use the getCentroid and add the result to the map

Categories