Skip to content

Commit

Permalink
Benymng/setup google geoncoding api (#130)
Browse files Browse the repository at this point in the history
---------

Co-authored-by: Shahan Neda <shahan.neda@gmail.com>
  • Loading branch information
benymng and shahanneda authored May 17, 2024
1 parent c44fa4d commit 2964079
Show file tree
Hide file tree
Showing 4 changed files with 93 additions and 15 deletions.
1 change: 1 addition & 0 deletions backend/app/graphql/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ class RootMutation(
def init_email_service(app):
print("Initializing email service")
if app.config["TESTING"]:
os.environ["ENV"] = "testing"
print("Using mock email service in testings!")
services["email_service"] = MockEmailService(
logger=current_app.logger,
Expand Down
55 changes: 50 additions & 5 deletions backend/app/utilities/location_to_coordinates.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,60 @@
import os

import requests

GEOCODE_API_URL = "https://geocode.maps.co/search"
GEOCODE_API_KEY = os.getenv("GEOCODING_API_KEY")
BASE_URL = "https://maps.googleapis.com/maps/api/geocode/"
GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY")

USE_GOOGLE_API = os.getenv("USE_GOOGLE_API", "1") == "1"


# NOTE: It's important all the errors in this file have the "GEOCODING" string in them since the frontend uses that to determine if the error is a geocoding error
def getGeocodeFromAddress(organization_address):
if "PYTEST_CURRENT_TEST" in os.environ:
if os.getenv("ENV") == "testing":
print("MOCKING LATITUDE IN TESTING")
return [-11.1, 11.1]

if USE_GOOGLE_API:
return getGeocodeFromAddressGoogle(organization_address)
else:
return getGeocodeFromAddressGeocode(organization_address)


def getGeocodeFromAddressGoogle(organization_address):
response = requests.get(
'{base_url}{output_format}?address={address}"&key={api_key}'.format(
output_format="json",
base_url=BASE_URL,
address=organization_address,
api_key=GOOGLE_API_KEY,
)
)
try:
if response.status_code != 200:
raise Exception("GEOCODING: Failed to get coordinates from Geocode API")

response_json = response.json()
if (
len(response_json) == 0
or "results" not in response_json
or not response_json["results"]
):
raise Exception("GEOCODING: Failed to get coordinates from Geocode API")

return [
float(response_json["results"][0]["geometry"]["location"]["lng"]),
float(response_json["results"][0]["geometry"]["location"]["lat"]),
]
except Exception as e:
print("Failed when getting geoencoding from address!")
print("Response:", response_json)
print(f"Status code is: {response.status_code}")
print("e is: ", e)
raise Exception("GEOCODING: Failed to get coordinates from Geocode API")


def getGeocodeFromAddressGeocode(organization_address):
response = requests.get(
'{base_url}?q="{address}"&api_key={api_key}'.format(
base_url=GEOCODE_API_URL,
Expand All @@ -20,13 +64,14 @@ def getGeocodeFromAddress(organization_address):
)
try:
if response.status_code != 200:
raise Exception("Failed to get coordinates from Geocode API")
raise Exception("GEOCODING: Failed to get coordinates from Geocode API")

response_json = response.json()
if len(response_json) == 0:
raise Exception("Failed to get coordinates from Geocode API")
raise Exception("GEOCODING: Failed to get coordinates from Geocode API")
return [float(response_json[0]["lon"]), float(response_json[0]["lat"])]
except Exception as e:
print("Failed when getting geoencoding from address!")
print(f"Status code is: {response.status_code}")
raise e
print("e:", e)
raise Exception("GEOCODING: Failed to get coordinates from Geocode API")
26 changes: 21 additions & 5 deletions frontend/src/components/auth/Join.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -471,11 +471,27 @@ const Join = (): React.ReactElement => {
console.log(response);
navigate(JOIN_SUCCESS_PAGE);
} catch (e: unknown) {
toast({
title: "Failed to create account. Please try again.",
status: "error",
isClosable: true,
});
if (
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
e?.graphQLErrors &&
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
String(e.graphQLErrors[0]?.message).includes("GEOCODING")
) {
toast({
title:
"Failed to located address, please try entering more information or a different address!",
status: "error",
isClosable: true,
});
} else {
toast({
title: "Failed to create account. Please try again.",
status: "error",
isClosable: true,
});
}
// eslint-disable-next-line no-console
console.log(e);
logPossibleGraphQLError(e as ApolloError);
Expand Down
26 changes: 21 additions & 5 deletions frontend/src/pages/Settings.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -727,11 +727,27 @@ const Settings = (): React.ReactElement => {
logPossibleGraphQLError(e as ApolloError);
setIsLoading(false);

toast({
title: "Failed to save settings",
status: "error",
isClosable: true,
});
if (
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
e?.graphQLErrors &&
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
String(e.graphQLErrors[0]?.message).includes("GEOCODING")
) {
toast({
title:
"Failed to located address, please try entering more information or a different address!",
status: "error",
isClosable: true,
});
} else {
toast({
title: "Failed to create account. Please try again.",
status: "error",
isClosable: true,
});
}
}
};

Expand Down

0 comments on commit 2964079

Please sign in to comment.