Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Completed Lab 1 #17

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file added .DS_Store
Binary file not shown.
44 changes: 44 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,3 +38,47 @@
- Complete [Labs](lab)
- Complete [Assignment](assignment)

### Notes
- slider (https://codepen.io/lknarf/pen/KWzRed)
- simple statistics (https://simplestatistics.org/)
- Mapbox -gl (graphics) - js (https://docs.mapbox.com/mapbox-gl-js/examples/):: necessity if have more than 1000 points
- chroma.js (nice color scales)
- charting libraries (chartist.js, charts)
- turf.js(create geometries)
- lineArc:specify the coord of the center of the circle, draws arc
- use L.geoJSON(turf geojson feature) to add to map
- json minify (online tool to compress any json code you copy, removing breaks)
- add polygons/lines created from turf to maps by using LEAFLET
- stringify the result, copy and paste it.
- feature collection is not a polygon... so sometimes input wants a polygon and not a feature collectoin. Need to extract out the corresponding polygon.
- templates: way of updating strings with a variable. ${variable}
$.parseHTML(`<div class="shape" data-leaflet-id=${id}><h1>Current ID: ${id}</h1></div>
`) //use backticks so tht $.parseHTml can change the id
- $(#shapes).append
- jQuery, lookup by attribute s
- layer.on("mouseover", function(e){
e.target._leaflet_id.
// e is the event happeningwhen mouseover
})
- $('#shapes').append($.parseHTML(`<div class="shape" data-leaflet-id=${id}><h1>Current ID: ${id}</h1></div>`))

## Notes - 11 April
MAPBOX
- GEOCODE


- polyline.decode('string returned from API')
- If the mapbox API returns a list of points, can use turf.js to turn it into a line
revcoords = _.map(coords, function(coord){return coord[1], coord[0]}) // to flip the coords
- JSON.stringify(truf.lineString(revcoords))
- L.geoJSON(turf.lineString(revcoords)).addTo(map)

lab2
- allow
- get lat lng from the origina name
- decode the polyline that comes back --> polyline.decode





Binary file added lab/.DS_Store
Binary file not shown.
Binary file added lab/lab1/.DS_Store
Binary file not shown.
58 changes: 53 additions & 5 deletions lab/lab1/js/draw.js
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ in the sidebar.
Change the variable myRectangle to myRectangles and set it to equal an empty
array. Change the rest of your code to push new layers into the array.

Task 6: Connect sidebar and map
Task 6: Connect sidebar and map

The HTML in the sidebar and the Leaflet layers on the map and in our Javascript
variable can be linked by using the Leaflet ID. Modify the application so that
Expand All @@ -80,6 +80,8 @@ clicking on a shape in the sidebar will do one of the following:
sidebar and the myRectanges array)
- Anything else you can think of!

OH- must add the clikcability when creating the new shape in map.on!! not outside.

Task 7 (Stretch Goal): Reverse Task 6

Modify the application so moving your mouse over a rectangle on the map will
Expand All @@ -89,17 +91,18 @@ Moving your mouse outside of the circle should remove the highlighting.
===================== */

// Global Variables
var myRectangle;
var myShapes=[];

// Initialize Leaflet Draw
var drawControl = new L.Control.Draw({
draw: {
polyline: false,
polygon: false,
circle: false,
circle: true,
marker: false,
circlemarker: false,
rectangle: true

}
});

Expand All @@ -108,6 +111,51 @@ map.addControl(drawControl);
// Event which is run every time Leaflet draw creates a new layer
map.on('draw:created', function (e) {
var type = e.layerType; // The type of shape
var layer = e.layer; // The Leaflet layer for the shape
var id = L.stamp(layer); // The unique Leaflet ID for the layer
myShapes.push(e.layer);; // The Leaflet layer for the shape
var id = L.stamp(e.layer); // The unique Leaflet ID for the layer
//console.log(id);
//console.log(myShapes);
_.each(myShapes, function(x){map.addLayer(x);});

// add id to sidebar
// call div using #, call class using .
$('#shapes').append($.parseHTML(`<div class="shape" data-leaflet-id=${id}><h1>Current ID: ${id}</h1></div>`));

// add functionality for clicking side bar, part 6
$('.shape').click(function () {
var clicked_id = $(this).attr('data-leaflet-id');
//alert('clicked');
console.log(clicked_id);
// remove old shapes
_.each(myShapes, function(x){map.removeLayer(x)});
// filter out to new shapes
myShapes = _.filter(myShapes, function(x){return x._leaflet_id != clicked_id})
// plot new shapes
_.each(myShapes, function(x){map.addLayer(x);});

});

/* alternative to part 6. Simply adding a click functionality to this div
$(`div[data-leaflet-id |=${id}]`).click(function(){
})*/

// part 7:
e.layer.on("mouseover", function(e){
var hovered = e.target._leaflet_id;
// div selector
$(`div[data-leaflet-id |=${hovered}]`).css("background-color", "yellow");
// |= is a pipe... it is a selector.
});
// have to do a mouseout as well, so that it doesnt stay highlighted
e.layer.on("mouseout", function(e){
var hovered = e.target._leaflet_id;
// div selector
$(`div[data-leaflet-id |=${hovered}]`).css("background-color", "white");
// |= is a pipe... it is a selector.
});



});


1 change: 0 additions & 1 deletion lab/lab1/js/setup.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,3 @@ var Stamen_TonerLite = L.tileLayer('http://{s}.basemaps.cartocdn.com/light_all/{
maxZoom: 20,
ext: 'png'
}).addTo(map);

5 changes: 4 additions & 1 deletion lab/lab2/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -19,18 +19,21 @@
<div id="map" class="map"></div>
<!-- Sidebar -->
<div class="sidebar">
<h1>Generating Routes</h1>
<h1>Generating Routes (Driving)</h1>
<h2 class="h3">From <span style="color:blue">here</span> to <span style="color:red">there</span></h2>
<label for="dest">Enter a destination</label>
<input id="dest" type="text">
<button id="calculate" disabled>Calculate Route</button>
<h2 id="distance"></h1>
<h2 id="duration"></h2>
</div>
<!-- Javascript Imports -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js" integrity="sha256-obZACiHd7gkOk9iIL/pimWMTJ4W/pBsKu+oZnSeBIek=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.3.1/leaflet.js" integrity="sha256-CNm+7c26DTTCGRQkM9vp7aP85kHFMqs9MhPEuytF+fQ=" crossorigin="anonymous"></script>
<script src='https://api.mapbox.com/mapbox.js/v3.1.1/mapbox.js'></script>
<script src="https://cdn.jsdelivr.net/npm/@mapbox/[email protected]/src/polyline.min.js"></script>
<script src='https://unpkg.com/@turf/turf/turf.min.js'></script>
<script src="js/setup.js"></script>
<script src="js/main.js"></script>
</body>
Expand Down
76 changes: 71 additions & 5 deletions lab/lab2/js/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ which allow us to rapidly prototype API requests.
I suggest Postman, which is available for free in the chrome app store. It provides
a cleaner, easier way to test ajax calls than simply using the console.

use postman to communicate with servers?? request made to API

Task 1: Use Mapbox's 'Search' API to 'geocode' information from your input

Expand All @@ -67,6 +68,12 @@ Questions you should ask yourself:
- What can I do with the output?
- Can I get a lat/lng from the output?

TrY to use the something in Jquery??

input will be a user specified destination
need to save that as a variable
input the variblae into the link


Task 2: Use Mapbox's 'Navigation' API to generate a route based on your origin and destination

Expand All @@ -77,6 +84,11 @@ Again, the task is somewhat underspecified. Let's start with the simplest routin
option available. Once you're getting a valid (as best you can tell) response
from the server, move to the next task.

record,record,record
in form lng,lat
go up to postman, replace {coords} with the 'record, record, record'

playground shows you what is possible, but postman shows how you can use the API

Task 3: Decode your route response

Expand Down Expand Up @@ -130,6 +142,25 @@ var goToOrigin = _.once(function(lat, lng) {
map.flyTo([lat, lng], 14);
});

// global variables for coords
var origin;
var destination;
var end_marker;
var route_feature;
var the_route;
var your_mapbox_token='pk.eyJ1IjoibGVhbm5lY2hhbiIsImEiOiJjazh1bGt2eWowY2k0M2ZtaDY3c2RiZnhyIn0.O9fZnzCKgPFTRAuDyWhRew';

// create functions
var geolocate = function(location){
var req= $.ajax(`https://api.mapbox.com/geocoding/v5/mapbox.places/${location}.json?access_token=${your_mapbox_token}`);
return req;
}

var getRoute = function(start, end){
var req= $.ajax(`https://api.mapbox.com/directions/v5/mapbox/driving/${start[0]},${start[1]};${end[0]},${end[1]}?access_token=${your_mapbox_token}&geometries=geojson`);
return req
}


/* Given a lat and a long, we should create a marker, store it
* somewhere, and add it to the map
Expand All @@ -146,13 +177,12 @@ $(document).ready(function() {
/* This 'if' check allows us to safely ask for the user's current position */
if ("geolocation" in navigator) {
navigator.geolocation.getCurrentPosition(function(position) {
origin = [position.coords.longitude, position.coords.latitude];
updatePosition(position.coords.latitude, position.coords.longitude, position.timestamp);
});
} else {
alert("Unable to access geolocation API!");
}


/* Every time a key is lifted while typing in the #dest input, disable
* the #calculate button if no text is in the input
*/
Expand All @@ -163,12 +193,48 @@ $(document).ready(function() {
$('#calculate').attr('disabled', false);
}
});

// click handler for the "calculate" button (probably you want to do something with this)
// NEED TO EXCECUTE IN THE DONE FUNCTION!!!
$("#calculate").click(function(e) {
var dest = $('#dest').val();
console.log(dest);
if (end_marker != undefined) {
map.removeLayer(end_marker);
};
if (route_feature != undefined) {
map.removeLayer(route_feature);
};

// first get the coordinates of the destination
geolocate(dest).done(function(response){
// return first coordinate
destination = response.features[0].center;
console.log(destination);
// next, get the route to the destination
getRoute(origin, destination).done(function(x){
the_route=x;

// returns a partial geojson(?), it cant be plotted directly. must extract arrays of coords
var route_coords = x.routes[0].geometry.coordinates;
var distance =(x.routes[0].distance).toFixed(2); //meters
var duration = (x.routes[0].duration / 60).toFixed(2); //sec
// $('#information').append($.parseHTML(`<div class="dist"><h3>Distance to Drive: ${distance} Meters</h3></div>
// <div class="dura"><h3>Duration of Drive: ${duration} minutes</h3></div>`))
$('#distance').text(`Distance: ${distance} meters`);
$('#duration').text(`Duration: ${duration} minutes`);
// now use turf.js to create a feature to be plotted. THIS IS A GEOJSON!
// NOTE! THERE IS NO NEED TO TRANSFORM THE ARRAY INTO A STRING! linestring takes in 2D array and not a string.
linestring = turf.lineString(route_coords, {name: 'Driving Route'});
// add the marker and geoJSON to map
end_marker = L.marker([destination[1], destination[0]]).addTo(map).bindPopup('Destination');
route_feature=L.geoJSON(linestring).addTo(map);
// change zoom on map
// need to swap around the lat and lngs
for (var i = 0; i < route_coords.length; i++) {route_coords[i] = [route_coords[i][1], route_coords[i][0]]};
map.fitBounds(route_coords);

});
});

});

});