def getLocation(self, input_location): location = Nominatim().geocode(input_location, language='en_US') return location
import psycopg2 from geopy.geocoders import Nominatim geolocator = Nominatim(user_agent="ex1") def get_longitude_latitude(geocode): return geocode.latitude, geocode.longitude try: con = psycopg2.connect(database="dvdrental", user="******", password="******", host="127.0.0.1", port="5433") print("Database opened successfully") except: print("I am unable to connect to the database") cur = con.cursor() cur.execute("SELECT * FROM GetAddresses()") addresses_rows = cur.fetchall() for row in addresses_rows: address, address2 = row longitude = 0 latitude = 0 if address is not None:
def revgeoloc(loc): geo = Nominatim() pos = geo.reverse((tuple(loc))[0:2], exactly_one=True) address = (pos.raw['display_name']).split(",") return address
popup = folium.Popup(branca.element.IFrame(html=html, width=420, height=320), max_width=2137) folium.Marker([coords[1], coords[0]], icon=icon, popup=popup).add_to(folium_map) else: test = folium.Html(photo, script=False) popup = folium.Popup(test, max_width=2650) folium.Marker([coords[1], coords[0]], icon=icon,popup=popup).add_to(folium_map) repeats.append(coords) help = help + 1 ''' if lat and lon: geolocator = Nominatim(user_agent="Kamerka") location = geolocator.reverse(coordinates, language='en') if location.address is None: res['error'] = 'No address was found for your coordinates' print(json.dumps(res)) sys.exit() string_printers = "geo:" + coordinates + "," + radius + " device:printer" string_cameras = "geo:" + coordinates + "," + radius + " device:webcam" if camera: cameras_results = shodan_query(string_cameras, 'camera') if cameras_results: res['data']['camera'] = draw_map(cameras_results, lat, lon, 'camera') if printer:
from geopy.geocoders import Nominatim import time try: city_list = [ "Athina", "Paris", "St. Louis", "London", "Stockholm", "Antwerpen", "Chamonix", "Amsterdam", "Sankt Moritz", "Los Angeles", "Lake Placid", "Berlin", "Garmisch-Partenkirchen", "Helsinki", "Oslo", "Cortina d'Ampezzo", "Melbourne", "Squaw Valley", "Roma", "Innsbruck", "Tokyo", "Mexico City", "Grenoble", "Munich", "Sapporo", "Montreal", "Moskva", "Sarajevo", "Calgary", "Seoul", "Barcelona", "Albertville", "Lillehammer", "Atlanta", "Nagano", "Sydney", "Salt Lake City", "Torino", "Beijing", "Vancouver", "Sochi", "Rio de Janeiro" ] count = 0 geolocator = Nominatim(user_agent="whatever") for city in city_list: if count % 15 == 14: time.sleep(3) city_info = geolocator.geocode(city) count += 1 print(city + ", " + str(city_info.latitude) + ", " + str(city_info.longitude)) except: print("Exception occured!") print("Last city information retreived - ", city_list[city_list.index(city) - 1])
from sqlalchemy.orm import sessionmaker Base = declarative_base() import random import string # random user name 8 letters def randomword(): letters = string.ascii_lowercase return "".join(random.choice(letters) for i in range(8)) # reverse the location (lan, lon) -> location detail g = Nominatim(user_agent=randomword()) ACTIVITY_KEYS = [ "run_id", "name", "distance", "moving_time", "type", "start_date", "start_date_local", "location_country", "summary_polyline", "average_heartrate", "average_speed", ]
import datetime from translitua import translit from django.db import models from django.contrib.gis.db import models as geomodels from django.urls import reverse from django.utils.text import slugify from django.contrib.auth.models import User from geopy.geocoders import Nominatim geolocator = Nominatim(timeout=7, user_agent='houses') class House(models.Model): geometry = geomodels.PointField( verbose_name='Місце на мапі', extent=(31.00, 49.00, 33.00, 50.00), help_text='<em>Просто поставте маркер на карту</em>') @property def lat_lng(self): return list(getattr(self.geometry, 'coords', [])[::-1]) # GENERAL FIELDS type_offer = models.CharField(max_length=50, verbose_name="Тип оголошення", choices=(('sale', 'Продаж'), ('rent', 'Оренда довгострокова')), default='SALE') title = models.CharField(max_length=70, verbose_name='Заголовок', help_text='70 знаків',
if 'lat_dd' in pmpg_chart.keys() and 'lon_dd' in pmpg_chart.keys(): pmpg_chart['lon_lamx'], pmpg_chart['lat_lamy'] = \ convert_LatLong_to_Lambert( pmpg_chart['lat_dd'], -1*pmpg_chart['lon_dd'] ) # (3) address to lat-long to CLCC if 'well_site_address' in pmpg_chart.keys() and \ 'well_site_city' in pmpg_chart.keys() and \ 'well_site_state' in pmpg_chart.keys(): from geopy.geocoders import Nominatim from geopy.exc import GeocoderTimedOut nom = Nominatim(user_agent="isws-iwip-app") result = nom.geocode('900 S CENTRAL AVENUE, Roxana, IL') geo_results = [] for iii in pmpg_chart.index: try: result = geocode_address( pmpg_chart.loc[iii, 'well_site_address'] + ' ,' + \ pmpg_chart.loc[iii, 'well_site_city'] + ' ,' + \ pmpg_chart.loc[iii, 'well_site_state'], nom) pmpg_chart.loc[iii, 'geo_addr'] = result[0] pmpg_chart.loc[iii, 'geo_lat'] = result[1] pmpg_chart.loc[iii, 'geo_lon'] = result[2]
matching_work_regime.append(" ") not_matching_work_regime.append(work_regime) count[i - 1] = count[i - 1] + counts #remote and location places = [] latitude = [] longitude = [] location_string = '' location = single_profile_data[4] counts = 0 places.append(job_location) places.append(location) geolocator = Nominatim(user_agent="http") for q in range(len(places)): locate = geolocator.geocode(places[q]) latitude.append(locate.latitude) longitude.append(locate.longitude) first = (latitude[0], longitude[0]) second = (latitude[1], longitude[1]) location_string = location + ' ' + str(great_circle(first, second).km) if (int(great_circle(first, second).km) <= 50): counts = counts + 1 matching_location.append(location_string) not_matching_location.append(" ") elif (int(great_circle(first, second).km) > 50): counts = 0 matching_location.append(" ")
def get(self, request): place = request.GET.get("ct") inner_place = request.GET.get("ict") global i_place_lat, i_place_lon, agent_lat, agent_lon, source_lat_lon, ict_bounding_box, nearest_agents, new_list3 ict_bounding_box = [] geolocator = Nominatim(user_agent="app") location = geolocator.geocode( inner_place) #Getting details of the place(city) temp = location.raw.get("boundingbox") ict_bounding_box = [float(x) for x in temp] i_place_lat = location.latitude i_place_lon = location.longitude source_lat_lon = (i_place_lat, i_place_lon) print("Finding Nearest Agents. Please Wait !!") new_list3 = [] try: with open(os.getcwd() + "/app/zipcodes/AmericaZipCodes.csv", 'r') as read_obj: # opening Zipcode CSV File csv_reader = reader(read_obj) new_list = [] list_of_rows = list(csv_reader) for data in list_of_rows: if data[2] == place and data[ 1] == inner_place: # Finding for the State and City in AmericaZipcodeFile new_list.append(data) continue new_list2 = [] for data2 in new_list: try: am = Agents_Details_Model.objects.filter( ZIPCODE=data2[0] ) # Filtering the Available Agents record whose zipcode matches with the AmericaZipcode Files for res in am: if int(data2[0]) == res.ZIPCODE: new_list2.append(res) else: pass except Agents_Details_Model.DoesNotExist: pass for res2 in new_list2: if res2 not in new_list3: new_list3.append( res2) # Filtering the duplicate records except FileNotFoundError: print("ZipCodeFile List Not Found") nearest_agents = [] if new_list3: for details in new_list3: # Finding the nearest agents geolocator1 = Nominatim(user_agent="app") try: agent_location = geolocator1.geocode( details.ADDRESS.rstrip('0123456789')) agent_lat = agent_location.latitude agent_lon = agent_location.longitude dest_lat_lon = (agent_lat, agent_lon) if agent_lat >= ict_bounding_box[ 0] and agent_lon >= ict_bounding_box[ 2]: # Finding the agents using boundingbox technique miles = round( distance.distance(source_lat_lon, dest_lat_lon).miles, 3) nearest_agents.append({ "miles": miles, "details": details }) else: pass except: pass else: return render( request, "nearest_agent.html", { "agents": nearest_agents[:100], "ct": place, "ict": inner_place }) else: print("No Agnets") print(nearest_agents) return render(request, "nearest_agent.html", { "agents": [], "ct": place, "ict": inner_place })
new_1.reset_index() # In[22]: new_2 = split(new_1) # In[52]: new_lst = together(new_1, new_2) # In[53]: city = 'Singapore' geolocator = Nominatim(user_agent="sin_explorer") location = geolocator.geocode(city) latitude = location.latitude longitude = location.longitude print('The geograpical coordinate of Singapore are {}, {}.'.format( latitude, longitude)) # In[54]: CLIENT_ID = 'WFK1SF3GTUYLQUHZ15BDG1XOEBSVEAMLQ3DMUWKTJAZOCFGH' # your Foursquare ID CLIENT_SECRET = 'G1ZQ50ZJ5XIOFMYYCOD1OWG5BCMGR4GDA0ZYTIJLB1XKLD2A' # your Foursquare Secret VERSION = '20180604' LIMIT = 500 # In[55]:
from geopy.geocoders import Nominatim # pip install geopy locator = Nominatim(user_agent="myGeocoder") addresses = [ "Garland", "Edmonton", "Oakland", "Pune", "Yangon", ] def get_coordinates(addresses: list): coordinates = [] for ad in addresses: loc = locator.geocode(ad, language='en',timeout=1000).raw co = (loc['lat'], loc['lon']) # print(loc) print(co) coordinates.append( co ) return coordinates def get_location(coordinates: list): locations = [] for c in coordinates: loc = locator.reverse(c, language='en', timeout=1000).raw print(loc) locations.append( loc ) return locations
def getName(coordinate): geolocator = Nominatim(user_agent="wheretogo") location = geolocator.reverse(coordinate) return location.address
async def weather(cmd, message, args): if args: location = ' '.join(args) else: await cmd.bot.send_message(message.channel, cmd.help()) return try: try: geolocator = Nominatim() loc_element = geolocator.geocode(location) latitude = loc_element.latitude longitude = loc_element.longitude except Exception as e: cmd.log.error(e) await cmd.bot.send_message( message.channel, 'Unable to retrieve coordinates for ' + location) return # Data Collection dark_sky_url = 'https://api.darksky.net/forecast/' + DarkSkySecretKey + '/' + str( latitude) + ',' + str(longitude) async with aiohttp.ClientSession() as session: async with session.get(dark_sky_url) as data: data = await data.json() try: today_forecast = data['hourly']['summary'] week_forecast = data['daily']['summary'] except: today_forecast = 'Nothing' week_forecast = 'Nothing' current = data['currently'] temp_f = current['temperature'] temp_c = (temp_f - 32) / 1.8 try: feel_f = current['apparentTemperature '] feel_c = (feel_f - 32) / 1.8 except: feel_f = temp_f feel_c = temp_c summary = current['summary'] precip_intensity_in = current['precipIntensity'] precip_intensity_cm = precip_intensity_in * 2.54 precip_chance = current['precipProbability'] * 100 try: precip_type = current['precipType'].title() except: precip_type = 'None' dew_point_f = current['dewPoint'] dew_point_c = (dew_point_f - 32) / 1.8 humidity = current['humidity'] * 100 wind_speed_mph = current['windSpeed'] wind_speed_kph = wind_speed_mph * 1.609344 if wind_speed_mph == 0: wind_bearing = 0 else: wind_bearing = current['windBearing'] try: visibility_mi = current['visibility'] visibility_km = visibility_mi * 1.60934 except: visibility_km = 0 visibility_mi = 0 cloud_cover = current['cloudCover'] * 100 pressure = current['pressure'] ozone = current['ozone'] # Data Output out_list = [] out_list.append(['Current State', summary]) out_list.append([ 'Temperature', str(format(temp_c, '.2f')) + '°C (' + str(temp_f) + '°F)' ]) out_list.append([ 'Feels Like', str(format(feel_c, '.2f')) + '°C (' + str(feel_f) + '°F)' ]) out_list.append([ 'Dew Point', str(format(dew_point_c, '.2f')) + '°C (' + str(dew_point_f) + '°F)' ]) out_list.append(['Humidity', str(humidity) + '%']) out_list.append(['Precipitation Type', precip_type]) out_list.append(['Precipitation Chance', str(precip_chance) + '%']) out_list.append([ 'Precipitation Intensity', str(format(precip_intensity_cm, '.2f')) + ' cmh (' + str(precip_intensity_in) + ' inh)' ]) out_list.append([ 'Wind Speed', str(format(wind_speed_kph, '.2f')) + ' KPH (' + str(wind_speed_mph) + ' MPH)' ]) out_list.append(['Wind Direction', str(wind_bearing) + '°']) out_list.append([ 'Visibility', str(format(visibility_km, '.2f')) + ' KM (' + str(visibility_mi) + ' MI)' ]) out_list.append(['Cloud Cover', str(cloud_cover) + '%']) out_list.append(['Pressure', str(pressure) + ' mb']) out_list.append(['Ozone Density', str(ozone)]) out_pretty_list = boop(out_list) out_text = 'Weather data for **' + location.title( ) + '**\nLocation: *(Lat: ' + str(latitude) + ', Long: ' + str( longitude) + ')*' out_text += '\n```haskell\n' + out_pretty_list + '\n```' forecasts = '```haskell\nUpcoming: \"' + today_forecast + '\"\nThis Week: \"' + week_forecast + '\"\n```\n' out_text += '\nForecasts:\n' + forecasts await cmd.bot.send_message(message.channel, out_text) except Exception as e: cmd.log.error(e) await cmd.bot.send_message(message.channel, 'Error Retrieving the data.')
import sys from pyspark.sql import SparkSession from geopy.geocoders import Nominatim import pyspark.sql.functions as F from pyspark.sql.types import * # Get geolocation of query address query_addr = sys.argv[2] output_filename = query_addr.replace(" ", "_") geolocator = Nominatim(user_agent="going_bakc_to_work") target_location = geolocator.geocode(query_addr) target_box = list(map(float, target_location.raw["boundingbox"])) start_lat = min(target_box[0], target_box[1]) end_lat = max(target_box[0], target_box[1]) start_lng = min(target_box[2], target_box[3]) end_lng = max(target_box[2], target_box[3]) # Utility functions def filter_location(lat, lng): ''' check if location in in target_box ''' if start_lat <= float(lat) and float( lat) <= end_lat and start_lng <= float(lng) and float( lng) <= end_lng: return True return False def get_datetime_tag(datetime):
def process(address, rented, type, price, description, lang): def myTranslate(text): if lang == 'en': return text response = client.translate_text( Text=text, SourceLanguageCode='en', TargetLanguageCode=lang ) return response['TranslatedText'] geolocator = Nominatim(user_agent="specify_your_app_name_here") location = geolocator.geocode(address, timeout=30) if location is None: return False house = False if 'condo' in type else True if not 'house' in type and not 'condo' in type: type = "Unknown" security = True if 'security' in description.lower() else False addressList = location.address.split(', ') fireStationCount = 0 breakins = 0 for add in addressList: add = add.replace('—', '-') if add in d.keys(): breakins = d[add] if add in fireStations.keys(): fireStationCount = fireStations[add] risk = breakins/36.4 if rented: risk *= 1.37 if house: risk *= 1.42 if security: risk *= (2/3) risk = round(risk, 2) print(risk) housemin = {} housemin['100K'] = 70 housemin['300K'] = 118 housemin['700K'] = 139 housemin['1.5M'] = 192 housemin['MAX'] = 301 housemax = 450 apartmentmin = {} apartmentmin['100K'] = 23 apartmentmin['300K'] = 29 apartmentmin['700K'] = 34 apartmentmin['1.5M'] = 48 apartmentmin['MAX'] = 73 apartmentmax = 120 premium = 0 diff = 0 minPremium = 0 price_nums = int("".join(filter(str.isdigit, price))) if house: if price_nums < 100000: diff = housemin['300K'] - housemin['100K'] minPremium = housemin['100K'] elif price_nums < 300000: diff = housemin['700K'] - housemin['300K'] minPremium = housemin['300K'] elif price_nums < 700000: diff = housemin['1.5M'] - housemin['700K'] minPremium = housemin['700K'] elif price_nums < 1500000: diff = housemin['MAX'] - housemin['1.5M'] minPremium = housemin['1.5M'] else: diff = housemax - housemin['MAX'] minPremium = housemin['MAX'] premium = minPremium + diff * risk/5 - diff * (fireStationCount - 1)/6 if rented: premium = premium * 1/2 else: if price_nums < 100000: diff = apartmentmin['300K'] - apartmentmin['100K'] minPremium = apartmentmin['100K'] elif price_nums < 300000: diff = apartmentmin['700K'] - apartmentmin['300K'] minPremium = apartmentmin['300K'] elif price_nums < 700000: diff = apartmentmin['1.5M'] - apartmentmin['700K'] minPremium = apartmentmin['700K'] elif price_nums < 1500000: diff = apartmentmin['MAX'] - apartmentmin['1.5M'] minPremium = apartmentmin['1.5M'] else: diff = apartmentmax - apartmentmin['MAX'] minPremium = apartmentmin['MAX'] premium = minPremium + diff * risk/5 - diff * (fireStationCount - 1)/6 if risk <= 2: neighbourhood = 'This property is in a LOW risk neighbourhood for breaking-and-entering, which DECREASES your insurance premium.' elif risk <= 4: neighbourhood = 'This property is in a MEDIUM risk neighbourhood for breaking-and-entering.' else: neighbourhood = 'This property is in a HIGH risk neighbourhood for breaking-and-entering, which INCREASES your insurance premium.' if rented: rentMessage = 'This property is listed as FOR RENT. Properties for rent are at higher risk of theft, but enjoy lower insurance premiums due to the landlord’s coverage.' else: rentMessage = 'This property is listed as FOR SALE. Properties for rent are at higher risk of theft, but enjoy lower insurance premiums due to the landlord’s coverage.' fireStationsMessage = 'This neighbourhood has ' + str(fireStationCount) + ' fire stations. Close proximity to fire stations lowers your insurance premium.' if 'house' in type: houseMessage = 'This property is listed as a ' + type.upper() + '. Houses and townhouses are at a higher risk of theft, which INCREASES your premium.' elif 'condo' in type: houseMessage = 'This property is listed as a CONDO. Condos are at a lower risk of theft, which DECREASES your premium.' else: houseMessage = 'Could not determine the type of this property.' premium = round(premium, 2) info = { 'address': address, 'price': price, 'rented': myTranslate('For Rent' if rented else 'For Sale'), 'type': myTranslate(type.capitalize()), 'risk': risk, 'riskColor': gen_risk_color(risk), 'premium': premium, 'description': myTranslate(description), 'security': security, 'stations': fireStationCount, 'resultPrompt': myTranslate('Result'), 'propertyTypePrompt': myTranslate('Property Type'), 'originalPostingPrompt': myTranslate('Visit original posting'), 'addressPrompt': myTranslate('Address'), 'pricePrompt': myTranslate('Price'), 'descriptionPrompt': myTranslate('Description'), 'insurancePremiumPrompt': myTranslate('Estimated Insurance Premium'), 'breakAndEnterPrompt': myTranslate('Risk of Breaking-and-Entering'), 'outOf5': myTranslate('out of 5'), 'neighbourhood': myTranslate(neighbourhood), 'rentVsSale': myTranslate('Rent versus Sale'), 'isForRent': myTranslate(rentMessage), 'proximity': myTranslate('Proximity to Fire Stations'), 'fireStationsCount': myTranslate(fireStationsMessage), 'pricePrompt': myTranslate('Price'), 'insurancePremiumInfluence': myTranslate('Insurance premiums are strongly influenced by the price of the property.'), 'houseMessage': myTranslate(houseMessage), 'houseTownhouseCondo': myTranslate('House/townhouse versus Condo'), 'higherScore': myTranslate("A higher score means higher risk"), 'checkAnother': myTranslate('Check another property'), 'month': myTranslate('month') } return info
def __init__(self): self.geolocator = Nominatim(user_agent="codefornl-covid19")
def signup(request): if request.method == 'POST': email = request.POST.get('email') name = request.POST.get('name') phone = request.POST.get('phone') password = request.POST.get('password') address = request.POST.get('address') usertype = request.POST.get('usertype') geolocator = Nominatim() loca = geolocator.geocode(address) print(loca.address) if usertype == 'Customer': user = Customer(name=name, email=email, phone=phone, address=address) user.set_password(user.make_password(password)) user.save() request.session['id'] = email request.session['type'] = 'customer' #customer = Customer.objects.get(email=request.session['id']) l1 = (loca.latitude, loca.longitude) t = Locuser() t.custid = email t.address_user = l1 t.save() elif usertype == 'Restaurant': rest = Restaurant.objects.all() test = 0 for x in rest: if (x.name == name): messages.error(request, "Restaurant with this name already exists") test = 1 return render(request, 'foodspark/login.html') if (test == 0): user = Restaurant(name=name, email=email, phone=phone, address=address) user.set_password(user.make_password(password)) user.save() request.session['id'] = email request.session['type'] = 'restaurant' l2 = (loca.latitude, loca.longitude) t = Locrest() t.restid = email t.address_rest = l2 t.save() elif usertype == 'DeliveryBoy': user = DeliveryBoy(name=name, email=email, phone=phone, address=address) user.set_password(user.make_password(password)) user.save() request.session['id'] = email request.session['type'] = 'deliveryboy' return redirect('/') if request.method == 'GET': return render(request, 'foodspark/login.html')
import re import time from datetime import datetime from random import randint from re import compile as recompile from urllib.parse import quote import pandas as pd import requests from bs4 import BeautifulSoup from geopy.geocoders import Nominatim import csv today = datetime.today().date() geolocator = Nominatim(user_agent='*****@*****.**') headers = { "User-Agent": 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) ' 'Chrome/84.0.4147.89 Safari/537.36' } class TooManyRequests(Exception): """raises in fetch_page function if request redirected to https://www.avito.ru/blocked""" pass def get_all_ads(query, sort_by='date', by_title=False, with_images=False,
def editDetails(request): if request.method == 'POST': if request.session['type'] == 'customer': customer = Customer.objects.get(email=request.session['id']) context = { 'customer': customer, } name = request.POST.get('name') phone = request.POST.get('phone') address = request.POST.get('address') city = request.POST.get('city') password = request.POST.get('password') print("ADDRESS") print(address) if name != "": customer.name = name if address != "": customer.address = address geolocator = Nominatim() loca = geolocator.geocode(address) print(loca.address) l1 = (loca.latitude, loca.longitude) t = Locuser.objects.get(custid=request.session['id']) t.address_user = l1 t.save() if city != "": customer.city = city if phone != "": customer.phone = phone if password != "": customer.set_password(customer.make_password(password)) customer.save() messages.success(request, 'Successfully saved :)') return render(request, 'foodspark/userdetails.html', context) elif request.session['type'] == 'deliveryboy': deliveryboy = DeliveryBoy.objects.get(email=request.session['id']) context = { 'deliveryboy': deliveryboy, } name = request.POST.get('name') phone = request.POST.get('phone') address = request.POST.get('address') city = request.POST.get('city') if name != "": deliveryboy.name = name if address != "": deliveryboy.address = address if city != "": deliveryboy.city = city if phone != "": deliveryboy.phone = phone deliveryboy.save() messages.success(request, 'Successfully saved :)') return render(request, 'foodspark/dbdetails.html', context) elif request.session['type'] == 'restaurant': restaurant = Restaurant.objects.get(email=request.session['id']) context = { 'restaurant': restaurant, } name = request.POST.get('name') phone = request.POST.get('phone') address = request.POST.get('address') res_type = request.POST.get('res_type') cuisine = request.POST.get('cuisine') city = request.POST.get('city') if phone != "": restaurant.phone = phone if address != "": restaurant.address = address if name != "": restaurant.name = name # restaurant.res_type = res_type if cuisine != "": restaurant.cuisine = cuisine if city != "": restaurant.city = city restaurant.save() messages.success(request, 'Successfully saved :)') return render(request, 'foodspark/restdetails.html', context) elif request.method == 'GET': return render(request, 'foodspark/details.html')
get_ipython().system('pip install geopy') from geopy.geocoders import Nominatim from geopy.extra.rate_limiter import RateLimiter from geopy.exc import GeocoderTimedOut from tqdm import tqdm import time import pandas as pd # view_box referes to the area of competence (+ what falls into the square). It was created manually using # https://boundingbox.klokantech.com/: -2.4602,53.1375,0.1985,54.6077 # view_box has the form: [Point(22, 180), Point(-22, -180)] geolocator = Nominatim(format_string=None, view_box=[(54.6077, 0.1985), (53.1375, -2.4602)], bounded=True, country_bias='gb-eng', domain='nominatim.openstreetmap.org', scheme=None, user_agent='my-application') def geocode_tweets_area(x): """ Apply Geopy. Import Nominatim and set the params for it. Use a time to sleep of 2 secs in the loop to avoid limit of 1query/sec Input: x: list of column data of addresses to be geolocated. for example:x= df['Street Found'].tolist() requirements: !pip install geopy from geopy.geocoders import Nominatim from geopy.extra.rate_limiter import RateLimiter from geopy.exc import GeocoderTimedOut
def run(self): # save startup time: from geopy.geocoders import Nominatim self.geolocator = Nominatim()
import networkx as nx import matplotlib.pyplot as plt from mpl_toolkits.basemap import Basemap as Basemap from geopy.geocoders import Nominatim import csv geolocator = Nominatim(user_agent="geoapiExercises") plt.figure(figsize=(10, 9)) #m = Basemap(projection='merc', llcrnrlon=-190, llcrnrlat=25, urcrnrlon=-60, urcrnrlat=50, lat_ts=0, resolution='i', suppress_ticks=True) m = Basemap(llcrnrlon=-160, llcrnrlat=-60, urcrnrlon=160, urcrnrlat=70, resolution='l', suppress_ticks=True) #m = Basemap(projection='merc',llcrnrlat=-80,urcrnrlat=80,llcrnrlon=-180,urcrnrlon=180,lat_ts=20,resolution='i',suppress_ticks=True) input_file = open('COVID19_Data_CSV.csv', "r") reader = csv.reader(input_file, delimiter=',') transmissions = [] dats = [] for line in reader: source = line[1].split(',')[0].lower().strip() destination = line[2].split(',')[0].lower().strip() transmissions.append((source, destination)) date = line[3] dats.append(date)
def make_geocoder(cls, **kwargs): kwargs.setdefault('user_agent', 'geopy-test') return Nominatim(**kwargs)
import os import pandas from geopy.geocoders import Nominatim # print(os.listdir()) df=pandas.read_json("supermarkets.json") df["Address"]=df["Address"]+", "+ df["City"]+", "+df["Country"] df["Coordinates"]=df["Address"].apply(Nominatim().geocode) df["Latitude"]=df["Coordinates"].apply(lambda x: x.latitude if x != None else None) df["Longitude"]=df["Coordinates"].apply(lambda x: x.longitude if x !=None else None) print(df) ##### ## OR for above code ##### # for i in df["Address"]: # nom1=Nominatim(user_agent="sags").geocode(i) # print(nom1.longitude) # df["Latitude"]=nom1.latitude # df["Longitude"]=nom1.longitude # df
def __init__(self): self.geo_locator = Nominatim(user_agent="poor_memory")
from geopy.geocoders import Nominatim from geopy.extra.rate_limiter import RateLimiter import folium geolocator = Nominatim(user_agent="main.py") geocode = RateLimiter(geolocator.geocode, min_delay_seconds=1) import info_twitter def get_locations_and_names(f_dict): """ (dict) -> dict This function returns a dictionary where the keys are the location of the friend and the values are their screen names (nicknames). """ locations_dict = {} for friend in f_dict["users"]: location = info_twitter.analyze_dictionary(friend['screen_name'], "location", f_dict) if location[-1] == ' ': location = location[:-1] if location not in locations_dict: locations_dict[location] = [] locations_dict[location].append(friend['screen_name']) return locations_dict def find_coordinates(location): """ (str) -> (str, str)
from bs4 import BeautifulSoup import urllib2 import csv import re import pandas as pd import locale import os from geopy.geocoders import Nominatim import sys reload(sys) # sys.setdefaultencoding('utf-8') geolocator = Nominatim(timeout=5) def update_locale(): locale.setlocale(locale.LC_ALL, 'deu_deu') def get_geo_info(addr_str): if len(addr_str.split(',')) > 2: region = addr_str.split(',')[-2][1:] else: region = addr_str.split(',')[-2] region_full = "%s, Muenchen" % region location = geolocator.geocode(region_full) if not location: # Try with larger area
import pandas as pd from geopy.geocoders import Nominatim import geocoder import csv geolocator = Nominatim() mydata = pd.read_csv('complaints_with_locations.csv') mydata = mydata.rename( columns={"Location (according to buggy OCR)": "Location"}) locations = mydata['Location'].apply(str) locations = locations + ", Berkeley" + ", CA" csvfileobj = open("coordinates.csv", "w") writer = csv.writer(csvfileobj) lat = [] lng = [] writer.writerow(['Latitude', 'Longitude']) for location in locations: chars = set( '/' ) #need this because geolocator doesn't find cross streets denoted by '/' if any((c in chars) for c in location): geocode = geocoder.google(location) lat.append(geocode.lat) lng.append(geocode.lng) else: try:
def station_area_location(df): print('Locating stations', end='') # Below the fire station addresses are scraped from the website. req = requests.get('https://sf-fire.org/fire-station-locations') soup = BeautifulSoup(req.content) addresses = soup.findAll('table')[0].findAll('tr') list_addresses = [[i.a for i in addresses][j].contents for j in range(len(addresses) - 1)] geolocator = Nominatim(timeout=60) list_addresses2 = [ list_addresses[i][0].replace('\xa0', ' ').split(' at')[0] for i in range(len(list_addresses)) ] list_addresses3 = [(list_addresses2[i] + ', San Francisco') for i in range(len(list_addresses2))] dot() # Determine the coordinates of each address, and also # impute certain coordinates using Google geo_list = [] [geo_list.append(geolocator.geocode(y)) for y in list_addresses3] geo_list = list(filter(None, geo_list)) geo_list2 = [geo_list[i][1] for i in range(len(geo_list))] geo_list2.insert(3, (37.772780, -122.389050)) # 4 geo_list2.insert(32, (37.794610, -122.393260)) # 35 geo_list2.insert(42, (37.827160, -122.368300)) # 48 del geo_list2[43] # Delete incorrect rows del geo_list2[43] geo_list2.insert(44, (37.801640, -122.455553)) # 51 geo_list2.insert(45, (37.622202, -122.3811767)) # A1 geo_list2.insert(46, (37.622202, -122.3811767)) # A2 geo_list2.insert(47, (37.622202, -122.3811767)) # A3 geo_list2.insert(48, (37.622202, -122.3811767)) geo_list2.insert(49, (37.622202, -122.3811767)) dot() df2_2 = df.copy() df2_2 = df2_2.loc[(df2_2.station_area != '94') & (df2_2.station_area != 'F3') & (df2_2.station_area != 'E2') & (df2_2.station_area != '47')] df2_2.station_area.fillna('999', inplace=True) dot() stations_list = df2_2['station_area'].unique() stations_list = pd.DataFrame(np.sort(stations_list)) station_capacity = [ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 999 ] starting_loc = pd.concat([ stations_list, pd.DataFrame(geo_list2), pd.DataFrame(station_capacity) ], axis=1) starting_loc.columns = ['station', 'lats', 'longs', 'stat_size'] df2_2['station_size'] = df2_2['station_area'].map( starting_loc.set_index('station')['stat_size']) df2_2['station_lat'] = df2_2['station_area'].map( starting_loc.set_index('station')['lats']) df2_2['station_long'] = df2_2['station_area'].map( starting_loc.set_index('station')['longs']) df2_2.reset_index(drop=True, inplace=True) print(' OK') return df2_2