-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathapp.py
161 lines (129 loc) · 5.95 KB
/
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
from flask import Flask, render_template, request, jsonify
import folium
from folium.plugins import MarkerCluster
import pandas as pd
import requests
from address_parser import parse_address
from geopy.distance import geodesic
from address_module import address_bp, extract_address_components
app = Flask(__name__)
app.register_blueprint(address_bp)
api_key = 'AIzaSyBMQPryqr_OhPX4lUtLBjB4YADGKJtUXkA'
# Load and prepare the dataset
df = pd.read_csv('VSKP.csv')
df = df.dropna(subset=['Latitude', 'Longitude'])
# Ensure Latitude and Longitude are valid
df['Latitude'] = pd.to_numeric(df['Latitude'], errors='coerce')
df['Longitude'] = pd.to_numeric(df['Longitude'], errors='coerce')
df = df[(df['Latitude'].between(-90, 90)) & (df['Longitude'].between(-180, 180))]
# Google Geocoding API
def geocode_address_google(address, api_key):
base_url = 'https://maps.googleapis.com/maps/api/geocode/json'
params = {'address': address, 'key': api_key}
response = requests.get(base_url, params=params)
results = response.json()
if results['status'] == 'OK':
location = results['results'][0]['geometry']['location']
lat, lng = location['lat'], location['lng']
# Validate the lat/lon returned by the API
if -90 <= lat <= 90 and -180 <= lng <= 180:
return lat, lng
else:
return None, None
else:
return None, None
# Find nearest BO based on coordinates
def find_nearest_bo(lat, lon, df):
nearest_bo = None
min_distance = float('inf')
for i, row in df[df['OfficeType'] == 'BO'].iterrows():
bo_location = (row['Latitude'], row['Longitude'])
distance = geodesic((lat, lon), bo_location).km
if distance < min_distance:
min_distance = distance
nearest_bo = row
return nearest_bo, min_distance
# Find PO with matching Pincode based on the coordinates
def find_po_by_pincode(pincode, df):
po_row = df[(df['OfficeType'] == 'PO') & (df['Pincode'] == pincode)]
return po_row
# Home route to render the form
@app.route('/')
@app.route('/', methods=['GET', 'POST'])
def index():
parsed_address = None
user_map = None
arranged_address = None
if request.method == 'POST':
address = request.form['address']
# Parse the address using Google Maps API
parsed_address = parse_address(address)
arranged_address = extract_address_components(address)
# Geocode the address for map generation
user_lat, user_lon = geocode_address_google(address, api_key)
if user_lat is not None and user_lon is not None:
map_center = [user_lat, user_lon]
mymap = folium.Map(location=map_center, zoom_start=12)
# Mark user's location
folium.Marker(
location=[user_lat, user_lon],
popup="Your Location",
icon=folium.Icon(color='blue', icon='info-sign')
).add_to(mymap)
# Find nearest BO
nearest_bo, distance_to_bo = find_nearest_bo(user_lat, user_lon, df)
if nearest_bo is not None:
folium.Marker(
location=[nearest_bo['Latitude'], nearest_bo['Longitude']],
popup=f"Nearest BO: {nearest_bo['OfficeName']} (Distance: {distance_to_bo:.2f} km)",
icon=folium.Icon(color='red', icon='info-sign')
).add_to(mymap)
# Find PO with the same Pincode as the nearest BO
po_row = find_po_by_pincode(nearest_bo['Pincode'], df)
if not po_row.empty:
po = po_row.iloc[0] # Take the first PO if there are multiple
folium.Marker(
location=[po['Latitude'], po['Longitude']],
popup=f"PO for BO's Pincode: {po['OfficeName']} (Pincode: {po['Pincode']})",
icon=folium.Icon(color='green', icon='info-sign')
).add_to(mymap)
# Save map to HTML and pass to the template
user_map = 'map.html'
mymap.save(f'static/{user_map}')
return render_template('index.html', parsed_address=parsed_address, user_map=user_map,arranged_address=arranged_address)
def get_map():
user_address = request.form['address']
user_lat, user_lon = geocode_address_google(user_address, api_key)
if user_lat is not None and user_lon is not None:
map_center = [user_lat, user_lon]
mymap = folium.Map(location=map_center, zoom_start=12)
# Mark user's location
folium.Marker(
location=[user_lat, user_lon],
popup="Your Location",
icon=folium.Icon(color='blue', icon='info-sign')
).add_to(mymap)
# Find nearest BO
nearest_bo, distance_to_bo = find_nearest_bo(user_lat, user_lon, df)
if nearest_bo is not None:
folium.Marker(
location=[nearest_bo['Latitude'], nearest_bo['Longitude']],
popup=f"Nearest BO: {nearest_bo['OfficeName']} (Distance: {distance_to_bo:.2f} km)",
icon=folium.Icon(color='red', icon='info-sign')
).add_to(mymap)
# Find PO with the same Pincode as the nearest BO
po_row = find_po_by_pincode(nearest_bo['Pincode'], df)
if not po_row.empty:
po = po_row.iloc[0] # Take the first PO if there are multiple
folium.Marker(
location=[po['Latitude'], po['Longitude']],
popup=f"PO for BO's Pincode: {po['OfficeName']} (Pincode: {po['Pincode']})",
icon=folium.Icon(color='green', icon='info-sign')
).add_to(mymap)
# Save to HTML and return it as a response
mymap.save('templates/map.html')
return render_template('map.html')
else:
return jsonify({'error': 'Address not found or invalid coordinates.'}), 400
if __name__ == '__main__':
app.run(host='127.0.0.1', port=5000, debug=True)