-
Notifications
You must be signed in to change notification settings - Fork 4
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
PCP - map feature #684
Open
jamesdoh0109
wants to merge
22
commits into
master
Choose a base branch
from
pcp_doh_newbie_location
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
PCP - map feature #684
Changes from 15 commits
Commits
Show all changes
22 commits
Select commit
Hold shift + click to select a range
68a3aec
Initial Backend Support for Longitude / Latitude of Buildings
shiva-menta 912d326
basic map functionality implementation using google maps api, hardcod…
jamesdoh0109 424915a
Fix No Room Bug
shiva-menta 1895569
map impl using leaflet + multiple location for courses fixed
jamesdoh0109 d4317da
Add Fetch Locations Management Command
shiva-menta 3c085f9
Add Query Parameter for Location
shiva-menta 39a2a60
map feature impl done (hyperlink on building name + map view for sche…
jamesdoh0109 e73fccb
map rerender bug fix
jamesdoh0109 e2f7ea2
map color coded pins done + fix minor bugs w not displaying correct s…
jamesdoh0109 a48e542
ts warning fix
jamesdoh0109 bf97bec
ts ignore leaflet types
jamesdoh0109 18b7b88
leaflet types upgrade + ts ignore
jamesdoh0109 58f5ecf
bump typescript
jamesdoh0109 26c168e
ts error fixed, search bar missing children
jamesdoh0109 ccf0f89
forbidden dark magic
jamesdoh0109 723640b
Merge In Master
shiva-menta a816f77
Merge branch 'pcp_doh_newbie_location' of github.com:pennlabs/penn-co…
shiva-menta ce14e3e
Fix Scraper for New Website Format
shiva-menta 9d7377d
Backend Lint
shiva-menta f0e2a3b
Remove Redundant meetings__room__building
shiva-menta a4b8ff1
frontend bug fixes + colored dot next to course items in map view
jamesdoh0109 896e9ec
dropdown to
jamesdoh0109 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Large diffs are not rendered by default.
Oops, something went wrong.
126 changes: 126 additions & 0 deletions
126
backend/courses/management/commands/fetch_building_locations.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,126 @@ | ||
import json | ||
from os import getenv | ||
from textwrap import dedent | ||
from typing import Dict, Optional, Tuple | ||
|
||
import requests | ||
from bs4 import BeautifulSoup | ||
from django.core.management.base import BaseCommand | ||
from googleapiclient.discovery import build | ||
from tqdm import tqdm | ||
|
||
from courses.models import Building | ||
|
||
|
||
def fetch_code_to_building_map() -> Dict[str, str]: | ||
response = requests.get( | ||
"https://provider.www.upenn.edu/computing/da/dw/student/building.e.html" | ||
) | ||
soup = BeautifulSoup(response.text, "html.parser") | ||
building_data = {} | ||
pre_tag = soup.find("pre") | ||
|
||
if pre_tag: | ||
text = pre_tag.get_text() | ||
lines = text.strip().split("\n") | ||
for line in lines: | ||
line = line.strip() | ||
parts = line.split(" ") | ||
building_data[parts[0].strip()] = " ".join(parts[1:]).strip() | ||
|
||
return building_data | ||
|
||
|
||
def get_address(link: str) -> str: | ||
response = requests.get(link) | ||
soup = BeautifulSoup(response.text, "html.parser") | ||
|
||
address_div = soup.find( | ||
"div", class_="text-white pb-3 mb-3 border-bottom border-1 border-indigo" | ||
) | ||
return address_div.get_text(separator=" ", strip=True) if address_div else "" | ||
|
||
|
||
def get_top_result_link(search_term: str) -> Optional[str]: | ||
api_key = getenv("GSEARCH_API_KEY") | ||
search_engine_id = getenv("GSEARCH_ENGINE_ID") | ||
|
||
full_query = f"upenn facilities {search_term} building" | ||
service = build("customsearch", "v1", developerKey=api_key) | ||
res = service.cse().list(q=full_query, cx=search_engine_id).execute() | ||
|
||
if "items" not in res: | ||
return None | ||
|
||
return res["items"][0]["link"] | ||
|
||
|
||
def convert_address_to_lat_lon(address: str) -> Tuple[float, float]: | ||
encoded_address = "+".join(address.split(" ")) | ||
api_key = getenv("GMAPS_API_KEY") | ||
|
||
response = requests.get( | ||
f"https://maps.googleapis.com/maps/api/geocode/json?address={encoded_address}&key={api_key}" | ||
) | ||
response_dict = json.loads(response.text) | ||
try: | ||
geometry_results = response_dict["results"][0]["geometry"]["location"] | ||
except BaseException: | ||
return None | ||
|
||
return {key: geometry_results[key] for key in ["lat", "lng"]} | ||
|
||
|
||
def fetch_building_data(): | ||
all_buildings = Building.objects.all() | ||
code_to_name = fetch_code_to_building_map() | ||
|
||
for building in tqdm(all_buildings): | ||
if not building.code: | ||
continue | ||
|
||
if building.latitude and building.longitude: | ||
continue | ||
|
||
query = code_to_name.get(building.code, building.code) | ||
link = get_top_result_link(query) | ||
if not link: | ||
continue | ||
|
||
address = get_address(link) | ||
if not address: | ||
continue | ||
|
||
location = convert_address_to_lat_lon(address) | ||
if not location: | ||
continue | ||
|
||
building.latitude = location["lat"] | ||
building.longitude = location["lng"] | ||
|
||
Building.objects.bulk_update(all_buildings, ["latitude", "longitude"]) | ||
|
||
|
||
class Command(BaseCommand): | ||
help = dedent( | ||
""" | ||
Fetch coordinate data for building models (e.g. JMHH). | ||
|
||
Expects GSEARCH_API_KEY, GSEARCH_ENGINE_ID, and GMAPS_API_KEY env vars | ||
to be set. | ||
|
||
Instructions on how to retrieve the environment variables. | ||
|
||
GSEARCH_API_KEY: https://developers.google.com/custom-search/v1/overview | ||
GSEARCH_ENGINE_ID: https://programmablesearchengine.google.com/controlpanel/all | ||
GMAPS_API_KEY: https://developers.google.com/maps/documentation/geocoding/overview | ||
""" | ||
) | ||
|
||
def handle(self, *args, **kwargs): | ||
if not all( | ||
[getenv(var) for var in ["GSEARCH_API_KEY", "GSEARCH_ENGINE_ID", "GMAPS_API_KEY"]] | ||
): | ||
raise ValueError("Env vars not set properly.") | ||
|
||
fetch_building_data() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,120 @@ | ||
import React, { useEffect } from "react"; | ||
import { MapContainer, TileLayer, useMap } from "react-leaflet"; | ||
import Marker from "../map/Marker"; | ||
import { Location } from "../../types"; | ||
|
||
interface MapProps { | ||
locations: Location[]; | ||
zoom: number; | ||
} | ||
|
||
function toRadians(degrees: number): number { | ||
return degrees * (Math.PI / 180); | ||
} | ||
|
||
function toDegrees(radians: number): number { | ||
return radians * (180 / Math.PI); | ||
} | ||
|
||
function getGeographicCenter( | ||
locations: Location[] | ||
): [number, number] { | ||
let x = 0; | ||
let y = 0; | ||
let z = 0; | ||
|
||
locations.forEach((coord) => { | ||
const lat = toRadians(coord.lat); | ||
const lon = toRadians(coord.lng); | ||
|
||
x += Math.cos(lat) * Math.cos(lon); | ||
y += Math.cos(lat) * Math.sin(lon); | ||
z += Math.sin(lat); | ||
}); | ||
|
||
const total = locations.length; | ||
|
||
x /= total; | ||
y /= total; | ||
z /= total; | ||
|
||
const centralLongitude = Math.atan2(y, x); | ||
const centralSquareRoot = Math.sqrt(x * x + y * y); | ||
const centralLatitude = Math.atan2(z, centralSquareRoot); | ||
|
||
return [toDegrees(centralLatitude), toDegrees(centralLongitude)]; | ||
} | ||
|
||
function separateOverlappingPoints(points: Location[], offset = 0.0001) { | ||
const validPoints = points.filter((p) => p.lat !== null && p.lng !== null) as Location[]; | ||
|
||
// group points by coordinates | ||
const groupedPoints: Record<string, Location[]> = validPoints.reduce((acc, point) => { | ||
const key = `${point.lat},${point.lng}`; | ||
(acc[key] ||= []).push(point); | ||
return acc; | ||
}, {} as Record<string, Location[]>); | ||
|
||
// adjust overlapping points | ||
jamesdoh0109 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
const adjustedPoints = Object.values(groupedPoints).flatMap((group) => | ||
group.length === 1 | ||
? group | ||
: group.map((point, index) => { | ||
const angle = (2 * Math.PI * index) / group.length; | ||
return { | ||
...point, | ||
lat: point.lat! + offset * Math.cos(angle), | ||
lng: point.lng! + offset * Math.sin(angle), | ||
}; | ||
}) | ||
); | ||
|
||
// include points with null values | ||
jamesdoh0109 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
return [...adjustedPoints, ...points.filter((p) => p.lat === null || p.lng === null)]; | ||
} | ||
jamesdoh0109 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
interface InnerMapProps { | ||
locations: Location[]; | ||
center: [number, number] | ||
} | ||
|
||
function InnerMap({ locations, center } :InnerMapProps) { | ||
const map = useMap(); | ||
|
||
useEffect(() => { | ||
map.flyTo({ lat: center[0], lng: center[1]}) | ||
}, [center[0], center[1]]) | ||
|
||
return ( | ||
<> | ||
<TileLayer | ||
// @ts-ignore | ||
attribution='© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors' | ||
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png" | ||
/> | ||
{separateOverlappingPoints(locations).map(({ lat, lng, color }, i) => ( | ||
<Marker key={i} lat={lat} lng={lng} color={color}/> | ||
))} | ||
</> | ||
) | ||
|
||
} | ||
|
||
function Map({ locations, zoom }: MapProps) { | ||
const center = getGeographicCenter(locations) | ||
|
||
return ( | ||
<MapContainer | ||
// @ts-ignore | ||
center={center} | ||
zoom={zoom} | ||
zoomControl={false} | ||
scrollWheelZoom={true} | ||
style={{ height: "100%", width: "100%" }} | ||
> | ||
<InnerMap locations={locations} center={center}/> | ||
</MapContainer> | ||
); | ||
}; | ||
|
||
export default React.memo(Map); |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
check for NaN
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
[centralLatitude ? centralLatitude : 39.9515, centralLongitude ? centralLongitude : -75.1910];
There's a check at the end of the function and I think this should be good