IEEE.org     |     IEEE Xplore Digital Library     |     IEEE Standards     |     IEEE Spectrum     |     More Sites

Unverified Commit b7d5cfab authored by tilley14's avatar tilley14 Committed by GitHub
Browse files

Merge pull request #98 from my-conservation-life/testingLeafletMap

Geometry Search Front End
parents 08e0edc8 73f41c51
/* eslint-disable vars-on-top */
/* eslint-disable no-console */
import { LightningElement } from 'lwc';
import leafletDraw from '@salesforce/resourceUrl/leafletDraw';
import utils from 'c/utils';
const DISTANCE_URL = utils.URL + 'assets/geometrySearch/distance';
// TODO import { assets, bboxAssets } from 'c/controllers';
// TODO import { markerFromAsset } from './utils';
const POLY_URL = utils.URL + 'assets/geometrySearch/polygon';
/* L is the Leaflet object constructed by the leaflet.js script */
/*global L*/
export default class GeoQuery extends LightningElement {
assetsPromise;
/**
* Starts the download for asset details and bounding box early.
*/
connectedCallback() {
// this.assetsPromise = assets.find({ projectId: parseInt(this.projectId, 10) });
// this.assetsBboxPromise = bboxAssets.get(parseInt(this.projectId, 10));
//Handled elsewhere
}
/**
......@@ -50,96 +48,144 @@ export default class GeoQuery extends LightningElement {
// Locks the map region to one earth (prevents dragging)
map.setMaxBounds([[-90,-180],[90,180]]);
var editableLayers = new L.FeatureGroup();
map.addLayer(editableLayers);
// Implement map "on click" handler
// If we could keep a reference to the map via a class variable (this.map = event.detail) this would be a lot cleaner
// to bad this map doesn't wish to cooperate at the time being.
map.on('click', function(e) {
// Remove the old radius search indicator so we can start a new query
if (this.mapCircle !== undefined) {
map.removeLayer(this.mapCircle);
}
// Remove the old markers from the previous query
if (this.myAssets !== undefined && this.myAssets.length > 0){
let i;
for (i = 0; i < this.myAssets.length; i++) {
map.removeLayer(this.myAssets[i]);
}
// Clear the markers
this.myAssets = [];
}
// Get the coordinates of where the user clicked
let coord = e.latlng;
console.log(`Map clicked at lat: ${coord.lat} lon: ${coord.lng}`);
// If you zoom out far enough the world map will start to repeat accross the screan and leaflet
// will return longitudes like 190 degrees for what would technically be -170
let mlat = (((coord.lat + 90) % 180) - 90);
let mlon = (((coord.lng + 180) % 360) - 180);
// Remember where the user actually clicked so we can put the markers in the correct spot
let latOff = Math.trunc(coord.lat / 90);
let lonOff = Math.trunc(coord.lng / 180);
console.log(`Translates to lat: ${mlat} lat offset: ${latOff} lon: ${mlon} lon offset: ${lonOff}`);
map.on('draw:created', function(e) {
var type = e.layerType,
layer = e.layer;
// radius in meters
let rad = 100000;
// Place the radius query indicator on the map
this.mapCircle = L.circle(coord, {
color: 'red',
fillColor: '#f03',
fillOpacity: 0.5,
radius: rad
}).addTo(map);
// Query the open source database for assets that are within a radius of
// where the user clicked... this should go in a controller module and is only
// here because I was hacking this together for a demo
const distanceURL = new URL(DISTANCE_URL);
distanceURL.searchParams.append('latitude', `${mlat}`);
distanceURL.searchParams.append('longitude', `${mlon}`);
distanceURL.searchParams.append('radiusMeters', `${rad}`);
console.log('Posting to: ' + distanceURL.href);
// Send out the request
this.assetsPromise = utils.post(distanceURL.href);
//Sets the icons for the trees
var baobabIcon = L.icon({
iconUrl: 'https://i.imgur.com/RQM5bdh.png',
iconSize: [32, 32]
});
// When the promise is fulfilled handle it
this.assetsPromise.then(response => {
// Response should be an array of assets
console.log(response);
//Sets the icon for lemurs
var lemurIcon = L.icon({
iconUrl: 'https://i.imgur.com/d2uKnLn.png',
iconSize: [32, 32]
});
// Initialize the array if need be
if ( this.myAssets === undefined) {
this.myAssets = [];
if (type === 'circle') {
//Gets the center point from the circle object
map.addLayer(layer);
var centerPnt = layer.getLatLng();
var center = [centerPnt.lng,centerPnt.lat];
console.log('The center point is ' + center);
//Gets the radius from the created circle object
let rad = layer.getRadius();
console.log('The radius is ' + rad);
//Adds the circle to the map
editableLayers.addLayer(layer);
console.log(`Map clicked at lat: ${centerPnt.lat} lon: ${centerPnt.lng}`);
//Gets the information needed for the query to the DB
const distanceURL = new URL(DISTANCE_URL);
distanceURL.searchParams.append('latitude', `${centerPnt.lat}`);
distanceURL.searchParams.append('longitude', `${centerPnt.lng}`);
distanceURL.searchParams.append('radiusMeters', `${rad}`);
console.log('Posting: ' + distanceURL.href);
// Send out the POST request
this.assetsPromise = utils.post(distanceURL.href);
// When the promise is fulfilled handle it
//Tried to break this entire block out into a separate method but the LWC gets weird when that happens.
this.assetsPromise.then(response => {
// Response should be an array of assets
console.log(response);
// Initialize the array if need be
if (this.myAssets === undefined) {
this.myAssets = [];
}
// Iterate over the assets and add them to the map
let assetIndex;
for (assetIndex = 0; assetIndex < response.length; assetIndex++) {
const assetResponse = response[assetIndex];
// Create the map marker, asset type determine the icon
let markerIcon;
if (assetResponse.asset_type === 'Tree') {
markerIcon = L.marker(L.latLng(assetResponse.lat, assetResponse.lon), {icon: baobabIcon}).addTo(map);
} else if (assetResponse.asset_type === 'Lemur') {
markerIcon = L.marker(L.latLng(assetResponse.lat, assetResponse.lon), {icon: lemurIcon}).addTo(map);
} else {
markerIcon = L.marker(L.latLng(assetResponse.lat, assetResponse.lon)).addTo(map);
}
// Add expanded details for if a user clicks on the marker
markerIcon.bindPopup(`${assetResponse.asset_type}\n\r${assetResponse.project_name}`);
// // Keep a reference to the marker so we can remove it later
this.myAssets.push(markerIcon);
}
});
}
if (type === 'polygon' || type === 'rectangle') {
map.addLayer(layer);
let polyLatLng = e.layer.getLatLngs();
console.log('The polygon is at ' + polyLatLng);
var body = {
coordinates: []
};
var vertices;
let polyPoints = polyLatLng[0].length;
let j;
for (j = 0; j < polyPoints; j++) {
vertices = {latitude: (polyLatLng[0][j]).lat, longitude: (polyLatLng[0][j]).lng};
body.coordinates.push(vertices);
}
// Iterate over the assets and add them to the map
let i;
for (i = 0; i < response.length; i++) {
const a = response[i];
// Create the map marker. Add back the offset so markers appear where the user clicked.
let m = L.marker(L.latLng(a.lat + (latOff * 90), a.lon + (lonOff * 180))).addTo(map);
// Add expanded details for if a user clicks on the marker
m.bindPopup(`${a.asset_type}\n\r${a.project_name}`);
// Keep a reference to the marker so we can remove it later
this.myAssets.push(m);
}
});
const polyURL = new URL(POLY_URL);
console.log('Posting: ' + polyURL.href);
// Send out the POST request
this.assetsPromise = utils.post(polyURL.href, body);
// When the promise is fulfilled handle it
this.assetsPromise.then(response => {
// Response should be an array of assets
console.log(response);
// Initialize the array if need be
if (this.myAssets === undefined) {
this.myAssets = [];
}
// Iterate over the assets and add them to the map
let assetIndex;
for (assetIndex = 0; assetIndex < response.length; assetIndex++) {
const assetResponse = response[assetIndex];
// Create the map marker. Add back the offset so markers appear where the user clicked.
let markerIcon;
if (assetResponse.asset_type === 'Tree') {
markerIcon = L.marker(L.latLng(assetResponse.lat, assetResponse.lon), {icon: baobabIcon}).addTo(map);
} else if (assetResponse.asset_type === 'Lemur') {
markerIcon = L.marker(L.latLng(assetResponse.lat, assetResponse.lon), {icon: lemurIcon}).addTo(map);
} else {
markerIcon = L.marker(L.latLng(assetResponse.lat, assetResponse.lon)).addTo(map);
}
// Add expanded details for if a user clicks on the marker
markerIcon.bindPopup(`${assetResponse.asset_type}\n\r${assetResponse.project_name}`);
// Keep a reference to the marker so we can remove it later
this.myAssets.push(markerIcon);
}
});
} else {
console.log('They shouldn\'t have been able to get here');
}
});
// this.map.on('click', this.onMapClicked);
}
}
}
<template>
<div class="map-root" lwc:dom="manual"></div>
</template>
\ No newline at end of file
<lightning-card title="Geospatial Map">
<div class="map-root" lwc:dom="manual"></div>
</lightning-card>
</template>
/* eslint-disable vars-on-top */
import { LightningElement } from 'lwc';
import { loadScript, loadStyle } from 'lightning/platformResourceLoader';
import leaflet from '@salesforce/resourceUrl/leaflet';
import leafletDraw from '@salesforce/resourceUrl/leafletDraw';
/* L is the Leaflet object constructed by the leaflet.js script */
/*global L*/
export default class Map extends LightningElement {
map; // L.map, a leaflet map. constructed in initializeleaflet
/**
* When the Map LWC is ready, start downloading Leaflet.
*
* When this is complete, call initializeleaflet()
*/
connectedCallback() {
Promise.all([
loadScript(this, leaflet + '/leaflet.js'),
loadStyle(this, leaflet + '/leaflet.css')
loadStyle(this, leaflet + '/leaflet.css'),
loadScript(this, leafletDraw + '/dist/leaflet.draw.js'),
loadStyle(this, leafletDraw + '/dist/leaflet.draw.css')
]).then(() => {
this.initializeLeaflet();
this.setupBaseTiles();
......@@ -38,8 +37,46 @@ export default class Map extends LightningElement {
L.control.scale().addTo(this.map);
this.map.setMinZoom(2);
this.map.setMaxZoom(17);
this.addDrawTools();
}
/**
* Adds the drawing tools to the map interface
*/
addDrawTools() {
var drawnItems = new L.FeatureGroup();
this.map.addLayer(drawnItems);
var drawControl = new L.Control.Draw({
draw: {
polygon: {
allowIntersection: false, //Disallows crossing over of lines in polygons
drawError: {
color: '#8B0000', //Turns darkred
message: '<strong>Intersecting lines not allowed<strong>'
},
shapeOptions: {
color: '#007300'
}
},
rectangle: {
showArea: false,
shapeOptions: {
color: '#e59400'
}
},
polyline: false,
marker: false,
circlemarker: false
},
edit: {
featureGroup: drawnItems,
remove: false,
edit: false
}
});
this.map.addControl(drawControl);
}
/**
* Setup the base OpenStreetMap tile layer
*/
......@@ -50,7 +87,6 @@ export default class Map extends LightningElement {
'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
{
attribution: '&copy; ' + mapLink + ' Contributors',
})
.addTo(this.map);
}).addTo(this.map);
}
}
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata" fqn="map">
<apiVersion>45.0</apiVersion>
<apiVersion>46.0</apiVersion>
<isExposed>false</isExposed>
</LightningComponentBundle>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<StaticResource xmlns="http://soap.sforce.com/2006/04/metadata">
<cacheControl>Public</cacheControl>
<contentType>application/zip</contentType>
</StaticResource>
\ No newline at end of file
Leaflet.draw Changelog
======================
## master
An in-progress version being developed on the master branch.
## 0.4.10 (July 3, 2017)
* Locking Leaflet version to 0.7.x-1.0.x
* Polygon line length, square kilometers and configurable precision
* fix for _getMeasurementString
* Locale number formatting added
## 0.4.2 (November 7, 2016)
### Improvements
* Documentation is now automatically generated
* L.Draw.Event is new, has all events in string format
### Bugfixes
* Travis tests
## 0.4.1 (October 21, 2016)
### Bugfixes
* fix markers becomming invisible when in edit mode
* Fix linking for EditPolyOptions
* Fixes very minor issue in readme with invalid variable name
## 0.4.0 (October 13, 2016)
### Improvements
* Add support for Leaflet 1.0.0+
### Bugfixes
* New L.Draw.Tooltip to mitigate L.Tooltip collision
### Potential Issues
* Several namespace changes, see BREAKINGCHANGES.md
* Cross support for both 0.7.0 and 1.0.0
## 0.3.0 (March 09, 2016)
### Improvements
* Add support for touch devices
* Corrected license
* Linter
### Bugfixes
* Added mouse handlers
* Fixed event listener leaks in Polyline
* Edit vertex event
## 0.2.4 (February 04, 2014)
### Improvements
* Add support for toolbar touch styles. (by [@alanshaw](https://github.com/alanshaw)). [#269](https://github.com/Leaflet/Leaflet.draw/pull/269 )
* Add support for maintaining a layers color when entering edit mode.
* Add support for showing area when drawing a rectangle.
* Refactor marker editing to bring in line with path editing handlers. Decouple setting editing style from edit toolbar. (by [@manleyjster](https://github.com/manleyjster)). [#323](https://github.com/Leaflet/Leaflet.draw/pull/323)
* Prevent skewing on selected edit marker. (by [@kyletolle](https://github.com/kyletolle)). [#341](https://github.com/Leaflet/Leaflet.draw/pull/341)
* Add support for changing the 'Radius' label text.
### Bugfixes
* Fix deleted layers LayerGroup constructor type. (by [@w8r ](https://github.com/w8r )). [#334](https://github.com/Leaflet/Leaflet.draw/pull/334)
## 0.2.3 (January 14, 2014)
### Improvements
* Restrict editing polygons so that at least 3 points are present. (by [@Zverik](https://github.com/Zverik)). [#200](https://github.com/Leaflet/Leaflet.draw/pull/200)
* Tooltips initially start hidden until the mouse has been moved. (by [@Zverik](https://github.com/Zverik)). [#210](https://github.com/Leaflet/Leaflet.draw/pull/210)
* Fixup spelling errors. (by [@nexushoratio](https://github.com/nexushoratio)). [#223](https://github.com/Leaflet/Leaflet.draw/pull/223)
* Combine ie specific style within leaflet.draw.css stylesheet. (by [@frankrowe](https://github.com/frankrowe)). [#221](https://github.com/Leaflet/Leaflet.draw/pull/221)
* Improve my terrible engrish. (by [@erictheise](https://github.com/erictheise)). [#237](https://github.com/Leaflet/Leaflet.draw/pull/237)
* Fire `editstart` events when a poly or simple shape is initially edited. (by [@atombender](https://github.com/atombender)). [#245](https://github.com/Leaflet/Leaflet.draw/pull/245)
* Add ability to add a new vertex to a polyline or polygon hander.
* Added ability to remove/undo the last placed point for polyline or polygons. (by [@Zverik](https://github.com/Zverik)). [#242](https://github.com/Leaflet/Leaflet.draw/pull/242)
* Dynamically position the action toolbars. (by [@DevinClark](https://github.com/DevinClark)). [#240](https://github.com/Leaflet/Leaflet.draw/pull/240)
* Improve polyline/polygon drawing by accepting some motion on click. (by [@atombender](https://github.com/atombender)). [#249](https://github.com/Leaflet/Leaflet.draw/pull/249)
* Only draw a limited number of guide dashes to improve performance in some rare cases. [#254](https://github.com/Leaflet/Leaflet.draw/pull/254)
### Bugfixes
* Fix edit toolbar so diabled state is represented correctly. (by [@joeybaker](https://github.com/joeybaker)). [#203](https://github.com/Leaflet/Leaflet.draw/pull/203)
* Fixed path middle marker positions. (by [@Zverik](https://github.com/Zverik)). [#208](https://github.com/Leaflet/Leaflet.draw/pull/208)
* Fix issue where toolbar buttons would have focus after clicked so couldn't use escape to cancel until clicked map at least once.
* Fix toolbar icons for retina displays. (by [@dwnoble](https://github.com/dwnoble)). [#217](https://github.com/Leaflet/Leaflet.draw/pull/217)
* Ensure that options are not shared between draw handler classes. (by [@yohanboniface](https://github.com/yohanboniface)). [#219](https://github.com/Leaflet/Leaflet.draw/pull/219)
* Fix bug where multiple handlers could be active. (by [@manubb](https://github.com/manubb)). [#247](https://github.com/Leaflet/Leaflet.draw/pull/247)
## 0.2.2 (October 4, 2013)
### Improvements
* Refactored the `L.drawLocal' object to be better structured and use this object whereever text is used. *NOTE: THIS IS A NEW FORMAT, SO WILL BRESK ANY EXISTING CUSTOM `L.drawLocal` SETTINGS*.
* Added Imperial measurements to compliment the existing Metric measurements when drawing a polyline or polygon.
* Added `draw:editstart` and `draw:editstop` events. (by [@bhell](https://github.com/bhell)). [#175](https://github.com/Leaflet/Leaflet.draw/pull/175)
* Added `repeatMode` option that will allow repeated drawing of features. (by [@jayhogan](https://github.com/jayhogan) and [@cscheid](https://github.com/cscheid)). [#178](https://github.com/Leaflet/Leaflet.draw/pull/178)
* Added abilit to set circle radius measurement to imperial units.
* Added disabled state for edit/delete buttons when no layers present. (inspired by [@snkashis](https://github.com/snkashis)). [#136](https://github.com/Leaflet/Leaflet.draw/pull/136)
* Add `showLength` and `showRadius` options to circle and polyline. (by [@Zverik](https://github.com/Zverik)). [#195](https://github.com/Leaflet/Leaflet.draw/pull/195)
* Add option to disable tooltips. (by [@Zverik](https://github.com/Zverik)). [#196](https://github.com/Leaflet/Leaflet.draw/pull/196)
### Bugfixes
* Fixed bug where edit handlers could not be disabled.
* Added support for displaying the toolbar on the right hand side of the map. (by [@paulcpederson](https://github.com/paulcpederson)). [#164](https://github.com/Leaflet/Leaflet.draw/pull/164)
* Add flexible width action buttons. (by [@Grsmto](https://github.com/Grsmto)). [#181](https://github.com/Leaflet/Leaflet.draw/pull/181)
* Check for icon existence before disabling edit state. (by [@tmcw](https://github.com/tmcw)). [#182](https://github.com/Leaflet/Leaflet.draw/pull/182)
* Only update guideslines when guidelines are present. (by [@jayhogan](https://github.com/jayhogan)). [#188](https://github.com/Leaflet/Leaflet.draw/pull/188)
* Fixes to localization code so it can be correctly set after files have been loaded.
* Fix for firing `draw:edit` twice for Draw.SimpleShape. (by [@cazacugmihai](https://github.com/cazacugmihai)). [#192](https://github.com/Leaflet/Leaflet.draw/pull/192)
* Fix last edit menu buttons from wrapping. (by [@moiarcsan](https://github.com/moiarcsan)). [#198](https://github.com/Leaflet/Leaflet.draw/pull/198)
## 0.2.1 (July 5, 2013)
### Improvements
* `draw:edited` now returns a `FeatureGroup` of features edited. (by [@jmkelly](https://github.com/jmkelly)). [#95](https://github.com/Leaflet/Leaflet.draw/pull/95)
* Circle tooltip shows the radius (in m) while drawing.
* Added Leaflet version check to inform developers that Leaflet 0.6+ is required.
* Added ability to finish drawing polygons by double clicking. (inspired by [@snkashis](https://github.com/snkashis)). [#121](https://github.com/Leaflet/Leaflet.label/pull/121)
* Added test environment. (by [@iirvine](https://github.com/iirvine)). [#123](https://github.com/Leaflet/Leaflet.draw/pull/123)
* Added `L.drawLocal` object to allow users to customize the text used in the plugin. Addresses localization issues. (by [@Starefossen](https://github.com/Starefossen)). [#87](https://github.com/Leaflet/Leaflet.draw/pull/87)
* Added ability to disable edit mode path and marker styles. (inspired by [@markgibbons25](https://github.com/markgibbons25)). [#121](https://github.com/Leaflet/Leaflet.label/pull/137)
* Added area calculation when drawing a polygon.
* Polyline and Polygon tooltips update on click as well as mouse move.
### Bugfixes
* Fixed issue where removing a vertex or adding a new one via midpoints would not update the edited state for polylines and polygons.
* Fixed issue where not passing in the context to `off()` would result in the event from not being unbound.(by [@koppelbakje](https://github.com/koppelbakje)). [#95](https://github.com/Leaflet/Leaflet.draw/pull/112)
* Fixed issue where removing the draw control from the map would result in an error.
* Fixed bug where removing points created by dragging midpoints would cause the polyline to not reflect any newly created points.
* Fixed regression where handlers were not able to be disabled.(by [@yohanboniface](https://github.com/yohanboniface)). [#139](https://github.com/Leaflet/Leaflet.draw/pull/139)
* Fixed bug where L.Draw.Polyline would try to remove a non-existant handler if the user cancelled and the polyline only had a single point.
## 0.2.0 (February 20, 2013)
Major new version. Added Edit toolbar which allows editing and deleting shapes.
### Features
* Consistant event for shape creation. (by [@krikrou](https://github.com/krikrou)). [#58](https://github.com/Leaflet/Leaflet.draw/pull/58)
### Bugfixes
* Fixed adding markers over vector layers. (by [@Starefossen](https://github.com/Starefossen)). [#82](https://github.com/Leaflet/Leaflet.draw/pull/82)
## 0.1.7 (February 11, 2013)
* Add sanity check for toolbar buttons when adding top and bottom classes. (by [@yohanboniface](https://github.com/yohanboniface)). [#60](https://github.com/Leaflet/Leaflet.draw/pull/60)
## 0.1.6 (January 17, 2013)
* Updated toolbar styles to be in line with the new Leaflet zoom in/out styles.
## 0.1.5 (December 10, 2012)
### Features
* Added 'drawing-disabled' event fired on the map when a draw handler is disabled. (by [@ajbeaven](https://github.com/thegreat)). [#35](https://github.com/jacobtoye/Leaflet.draw/pull/35)
* Added 'drawing' event fired on the map when a draw handler is actived. (by [@ajbeaven](https://github.com/thegreat)). [#30](https://github.com/jacobtoye/Leaflet.draw/pull/30)
### Bugfixes
* Stopped L.Control.Draw from storing handlers in it's prototype. (by [@thegreat](https://github.com/thegreat)). [#37](https://github.com/jacobtoye/Leaflet.draw/pull/37)
## 0.1.4 (October 8, 2012)
### Bugfixes