def post(self, request): mapbox_client = MapBox(settings.MAPBOX_API_KEY) location_json = json.loads(request.body) location = location_json["address"] result = mapbox_client.geocode(location) if result is None: return JsonResponse({"valid": False}) else: latitude = result.latitude longitude = result.longitude return JsonResponse({"valid": True, "latitude": latitude, "longitude": longitude})
def post(self, request, user_pk): if get_object_or_404(User, pk=user_pk) == request.user: form = MusicianForm(data=request.POST, files=request.FILES) if form.is_valid(): mapbox_client = MapBox(settings.MAPBOX_API_KEY) musician = form.save(commit=False) result = mapbox_client.geocode(musician.city) musician.latitude = result.latitude musician.longitude = result.longitude musician.user = request.user musician.save() return redirect(to='show-musician', musician_pk=musician.pk) return redirect(to="homepage") return redirect(to="homepage")
def address(request): """Return lat/lon for input address via json fetch.""" if request.method == "POST": print(request.body.decode('utf-8')) address = '{address}, {city}, {state} {zip}'.format( **json.loads(request.body.decode('utf-8'))) geolocator = MapBox(api_key=os.getenv('MB_TOKEN')) location = geolocator.geocode(address) new_loc = { 'lat_position': location.latitude, 'lon_position': location.longitude, } return JsonResponse(new_loc) else: return redirect('/')
def get(self, request): """ Respond to the get requests from the frontend Args: request (django.http.request): request from the frontend, which includes hour, origin and destination params Returns: JsonReponse (django.http.JsonResponse): GeoJson object of the shortest (safest) path (the path with fewest crashes) """ query_dict = request.query_params # get parameters from request hour = int(query_dict.get("hour")) origin = query_dict.get("origin") dest = query_dict.get("destination") # geocode origin and destination api_key = "pk.eyJ1Ijoib3Blbi1hZGRyZXNzZXMiLCJhIjoiSGx0a1B1NCJ9.2O1QelK6jnFXfDznC2pNSw" geocoder = MapBox(api_key=api_key, timeout=None) origin_lat, origin_lon = self._geocode(geocoder, origin) dest_lat, dest_lon = self._geocode(geocoder, dest) geojson = self._get_shortest_path_json(hour, origin_lon, origin_lat, dest_lon, dest_lat) return JsonResponse(geojson)
def make_json(properties): features = [] denver = ' Denver, CO' for row in properties: row_address_list = [row[14], row[15], row[16], row[17], denver] print(row_address_list) row_address = ' '.join(row_address_list) tax_address_list = [row[6], row[7], row[8], row[9], row[10], row[11], row[12]] tax_address = ' '.join(tax_address_list) locator = MapBox('pk.eyJ1IjoiYmFsZmFkb3J0aGVzdHJhbmdlIiwiYSI6ImNrZmNyNTJvYjB6cnQydXBlZWd4dGN2OHkifQ.fGHNFT7Aqk-dzH_7dp0tUg') location = locator.geocode(row_address) map_location = Point((location.longitude, location.latitude)) features.append(Feature(geometry=map_location, properties={'property_name': ' '.join(row[4]), 'property_address' : row_address, 'tax_address' : tax_address})) feature_collection = FeatureCollection(features) with open('static/properties.geojson', 'w') as f: dump(feature_collection, f)
def geocoding(ctx, query, apikey, forward, raw, display): """ MapBox's geocoding service. \f :param ctx: A context dictionary. :param query: A string to represent address query for geocoding. :param apikey: An API key for authentication. :param forward: A boolean flag for forward/reverse geocoding. :param raw: A boolean flag to show api response as it is. :param display: A boolean flag to show result in web browser. :return: None. """ apikey = apikey or os.environ.get("MAPBOX_APIKEY") if apikey is None: raise ApiKeyNotFoundError( "Please pass MAPBOX API KEY as --apikey or set it as environment " "variable in MAPBOX_APIKEY ") ctx.obj["apikey"] = apikey geolocator = MapBox(api_key=ctx.obj["apikey"]) if forward: location = geolocator.geocode(query) if raw: click.secho(json.dumps(location.raw, indent=2), fg="green") elif display: feature = get_feature_from_lat_lon(location.latitude, location.longitude) geo_display(feature) else: result = {"lat": location.latitude, "lon": location.longitude} click.secho(json.dumps(result, indent=2), fg="green") else: location = geolocator.reverse(query) if raw: click.secho(json.dumps(location.raw, indent=2), fg="green") else: click.secho(location.address, fg="green")
def search_nearest(self, update, context, place): # Typing... context.bot.send_chat_action(chat_id=update.effective_chat.id, action=ChatAction.TYPING) # Setup MapBox mapbox_token = os.environ.get("MAPBOX_TOKEN") geolocator = MapBox(mapbox_token) proximity = (45.464228552423435, 9.191557965278111) # Duomo location = geolocator.geocode(place, proximity=proximity) stations_full_info = self.pull_stations() station_raw = self.api.get_nearest_station(stations_full_info, location.latitude, location.longitude) reply_markup = self.tools.inline_keyboard_buttons(station_raw) # Generate Text Message station = self.print_result(station_raw) nearest_station = "The nearest station is: \n" + station # Send text update.message.reply_text( nearest_station, reply_markup=reply_markup, )
def geocode_locations(locations, logger, use_mapbox=True): if use_mapbox: # mapbox key stolen from node explorer :D geolocator = MapBox( api_key= "pk.eyJ1IjoiZGFkaWNvIiwiYSI6IlVaOVU3QmMifQ.dDoTL04V_WtMo2iQkfvZBg") else: geolocator = Nominatim(user_agent="edgenodelookup") geocode = RateLimiter(geolocator.geocode, min_delay_seconds=1, swallow_exceptions=False) def lookup(location): city, countrycode = [s.strip() for s in location.split(",")] logger.info(u"geocode processing {} {}".format(city, countrycode)) try: if use_mapbox: result = geocode(city, country=countrycode) else: result = geocode({"city": city}, country_codes=countrycode) except Exception as e: logger.error("geocode processing failed with {}".format(e)) return None if result is None: logger.warning( "geocode could not find {} {}. None is used.".format( city, countrycode)) return result decoded_location = locations.apply(lookup) decoded_location_non_nil = decoded_location[pd.notna( decoded_location)] #remove nil # seperate location object into parts latitudes = decoded_location_non_nil.apply(lambda loc: loc.latitude) longitudes = decoded_location_non_nil.apply(lambda loc: loc.longitude) addresses = decoded_location_non_nil.apply(lambda loc: loc.address) loc_df = pd.DataFrame({ "latitude": latitudes, 'longitude': longitudes, 'retrieved_address': addresses, 'explorer_location': locations.loc[pd.notna(decoded_location)] }) return loc_df
def get(self): args = parser.parse_args() # get parameters from requests hour, orig, dest = args['hour'], args['origin'], args['destination'] # geocode origin and destination api_key = "pk.eyJ1Ijoib3Blbi1hZGRyZXNzZXMiLCJhIjoiSGx0a1B1NCJ9.2O1QelK6jnFXfDznC2pNSw" geocoder = MapBox(api_key=api_key, timeout=None) origin_lat, origin_lon = self._geocode(geocoder, orig) dest_lat, dest_lon = self._geocode(geocoder, dest) geojson = self._get_shortest_path_json(hour, origin_lon, origin_lat, dest_lon, dest_lat) return geojson, 200, {'Access-Control-Allow-Origin': '*'}
def process_dict(d): if isinstance(d, VenueLocation): out = d.to_dict() vl = d else: if 'name' in d: del d['name'] if 'coor' in d: d['long'], d['lat'] = d['coor'] del d['coor'] out = d.copy() vl = VenueLocation.from_dict(d) if not out['long'] and vl.get_geocoord_key() in geocoords_by_key: out['long'], out['lat'] = geocoords_by_key[vl.get_geocoord_key()] elif 'train' in out['venue'].lower() or 'v/line' in out['venue'].lower( ): # Need to add public transport lines separately! pass elif not out['long']: if not GEOLOCATOR[0]: GEOLOCATOR[0] = MapBox(api_key=environ['MAPBOX_KEY'], user_agent="https://covid-19-au.com") try: location = GEOLOCATOR[0].geocode(out['venue'] + ', ' + out['area'] + ', ' + out['state'] + ', ' + 'Australia') print(out, location) if location: out['long'] = location.longitude out['lat'] = location.latitude except: # Make sure it doesn't keep trying to get the lat/long # when the service didn't find the location! import traceback traceback.print_exc() out['long'] = '!error' out['lat'] = '!error' return out
def make_geocoder(cls, **kwargs): return MapBox(api_key=env['MAPBOX_KEY'], timeout=3, **kwargs)
for i in range(10): for j in range(len(arr)): for k in range(len(arr[j])): if ((arr[j][k]) == clean[i]): if (j == 0): typ = "Groceries" elif j == 1: typ = "Fastfood" elif j == 2: typ = "Gas" else: typ = "Other" dat = datetime.datetime.now() geolocator = MapBox(api_key=mapbox_creds.API_KEY, user_agent="spendly-web") concat = "" for i in clean: concat = concat + " " + i print(concat) address = re.search( r"\d{1,4}[A-Z]?\s([NSEW]\.)?\s(\d{1,3}(st|nd|rd|th))?\s(\w\s)+([A-Z][a-z]{1,3}\.)?", concat) print(address) location = geolocator.geocode(address) timey = dat.strftime('%Y-%m-%d.%H:%M:%S')
' Administrative and Support and Waste Management and Remediation Services', '56' ], [' Educational Services', '61'], [' Health Care and Social Assistance', '62'], [' Arts, Entertainment, and Recreation', '71'], [' Accommodation and Food Services', '72'], [' Other Services', '81'], [' Religious Organizations', '8131'], [' Labor Unions and Similar Labor Organizations', '81393'], [' Political Organizations', '81394'], [' Private Households', '814'], [' Consumer Goods Repair', '811'], [' Personal Services', '812'], [' Government Support', '92'], [' Unclassified Establishments', '99'], [' Unreported Business Type', 'na'] ] geolocator = MapBox( api_key= 'pk.eyJ1IjoiZnV6enlsb2dpYzEzIiwiYSI6ImNrY2xjOGR5NTF4eWcycm5xYjY5eXA5ejUifQ.o3nz27PTtPI5JxztLiw_Tw' ) def testAddress(address): location = geolocator.geocode(address) print(location.address) print((location.latitude, location.longitude)) def addressCleanup(df, stateName): df['Zip'] = df['Zip'].fillna(0.0).astype(int) #, expand= True) df['Address'] = df.Address.str.split(pat='BLDG').str[0] df['Address'] = df.Address.str.split(pat='Bldg').str[0] df['Address'] = df.Address.str.split(pat='bldg').str[0]
def setUpClass(cls): cls.geocoder = MapBox(api_key=env['MAPBOX_KEY'], timeout=3)
) ] layout = go.Layout( autosize = True, hovermode = "closest", mapbox = dict(accesstoken = mapbox_access_token, bearing = 0, center = dict(lat = 38.900905, lon = -77.044784), pitch = 0, zoom = 10), ) fig = dict(data = data, layout = layout) py.plot(fig, filename = "Capital Bikeshare Locations") ## add city and state features mapbox = MapBox(api_key = mapbox_access_token) cabiLoc["CITY"] = "" for index, row in cabiLoc.iterrows(): cabiLoc["CITY"].iloc[index], cabiLoc["OWNER"].iloc[index] = cityandstate(lat = row["LATITUDE"], lon = row["LONGITUDE"], maps = mapbox) ## Manually change 31062 station to Arlington, VA rooseveltID = cabiLoc.index[cabiLoc["TERMINAL_NUMBER"] == 31062] cabiLoc["CITY"].iloc[rooseveltID] = "Arlington" cabiLoc["OWNER"].iloc[rooseveltID] = "VA" cabiLoc.to_csv("Capital Bikeshare Locations Clean.csv", index = False)
def homepage(request): response = requests.get( 'http://api.openweathermap.org/data/2.5/weather?q=kathmandu,np&appid=8d2de98e089f1c28e1a22fc19a24ef04' ) weather_data = response.json() print(weather_data["weather"]) # weather_dict={weather_data["weather"][i] for i in [0,]} source_latitude = 0 source_longitude = 0 destination_latitude = 0 destination_longitude = 0 travel_distance = 0 if request.method == 'POST': form = DestinationForm(request.POST) if form.is_valid(): form_data = form.save() address = "%s, %s" % (form_data.source, form_data.destination) geolocator = MapBox( api_key= 'pk.eyJ1IjoicmFuamFuNDM1IiwiYSI6ImNrNWIzdnNqeTE2ZjgzZG82OG40aG82ejcifQ.nrFTVyOERu6YhgS66Gxr8A' ) location_source = geolocator.geocode(form_data.source) location_destination = geolocator.geocode(form_data.destination) source_latitude = location_source.latitude source_longitude = location_source.longitude destination_latitude = location_destination.latitude destination_longitude = location_destination.longitude source = (source_latitude, source_longitude) destination = (destination_latitude, destination_longitude) str_geo = str(distance.distance(source, destination)) travel_distance = round(float(str_geo[:-3]), 2) print(travel_distance) pnt1 = GEOSGeometry('SRID=4326;POINT(%s %s)' % (source_latitude, source_longitude)) pnt2 = GEOSGeometry('SRID=4326;POINT(%s %s)' % (destination_latitude, destination_longitude)) print(pnt1.distance(pnt2) * 100) # location.destination = geolocator.geocode(form_data.destination) form = DestinationForm() #showing database information in map post_list = Post.objects.all() print(post_list[0].location.wkt) loc_list = [str(post.location) for post in post_list] temp = [loc.split(";") for loc in loc_list] point_list = [i[1] for i in temp] final = [(point[7:(len(point) - 1)]) for point in point_list] tempo = [a.split(" ") for a in final] lat = [i[0] for i in tempo] lon = [i[1] for i in tempo] latlon = [(float(lat[i]), float(lon[i])) for i in range(len(lon))] #showing sensor data sensor_data = SensorModel.objects.latest('id') #showing the number of vehicles vehicle_num = VehicleModel.objects.latest('id') return render( request, 'map/base_map.html', { 'form': form, 'source_latitude': source_latitude, 'source_longitude': source_longitude, 'destination_latitude': destination_latitude, 'destination_longitude': destination_longitude, 'distance': travel_distance, 'posts': post_list, 'location': latlon, 'weather_data': weather_data, 'sensor_data': sensor_data, 'vehicle_num': vehicle_num, }, ) # def databaseshow(request): # #showing post objects # post_list=Post.objects.all() # print (post_list[0].location.wkt) # loc_list=[str(post.location) for post in post_list] # temp=[loc.split(";") for loc in loc_list] # point_list=[i[1] for i in temp] # final=[(point[7:(len(point)-1)]) for point in point_list] # tempo=[a.split(" ") for a in final] # lat=[i[0] for i in tempo] # lon=[i[1] for i in tempo] # latlon=[(float(lat[i]),float(lon[i])) for i in range(len(lon))] # return render(request,'map/base_map.html',{'posts':post_list,'location':latlon})
import urllib.request, urllib.parse, urllib.error from scripts import twurl import json import ssl import folium from geopy.geocoders import MapBox from geopy.exc import GeocoderServiceError TWITTER_URL = 'https://api.twitter.com/1.1/friends/list.json' ctx = ssl.create_default_context() ctx.check_hostname = False ctx.verify_mode = ssl.CERT_NONE geolocator = MapBox( api_key= 'pk.eyJ1Ijoicm9tYW4yMjIzNCIsImEiOiJjanJ1b2lkdmgxNWhoNDNxc3B4Y2o0dnE4In0.-o_eVMh-dV2YuhI8qbtp-Q' ) def get_json(acct): if len(acct) > 1: url = twurl.augment(TWITTER_URL, {'screen_name': acct, 'count': '100'}) connection = urllib.request.urlopen(url, context=ctx) data = connection.read().decode() js = json.loads(data) loc = dict() for u in js['users']: loc[u['location']] = loc.get(u['location'], list()) loc[u['location']].append(u['screen_name']) return loc
def address_to_long_lat(city, state, addressline1, addressline2, postcode, country): """ :param city: e.g. :param state: e.g. :param addressline1: e.g. :param addressline2: e.g. :param postcode: e.g. :param country: e.g. :return: """ with open(SCRIPT_DIR / '..' / 'data' / 'geolocate_cache.json', 'r', encoding='utf-8') as f: portalocker.lock(f, portalocker.LOCK_SH) try: address_cache = json.loads(f.read()) finally: portalocker.unlock(f) address = [] if addressline2: address.append(addressline2) if addressline1: address.append(addressline1) if city: address.append(city) if state: address.append(state) if postcode: address.append(postcode) if country: address.append(country) address = ', '.join(address) if address in address_cache: item = address_cache[address] if item or True: return item if not GEOLOCATOR[0]: GEOLOCATOR[0] = MapBox(api_key=environ['MAPBOX_KEY'], user_agent='https://www.covid-19-au.com') try: location = GEOLOCATOR[0].geocode(address) if location: longlat = (location.longitude, location.latitude) except: # Make sure it doesn't keep trying to get the lat/long # when the service didn't find the location! traceback.print_exc() longlat = None time.sleep(1) address_cache[address] = longlat with open(SCRIPT_DIR / '..' / 'data' / 'geolocate_cache.json', 'w', encoding='utf-8') as f: portalocker.lock(f, portalocker.LOCK_EX) try: f.write(json.dumps(address_cache, ensure_ascii=False, indent=2)) finally: portalocker.unlock(f) return longlat
#!/usr/bin/python3 from geopy.geocoders import Nominatim from geopy.geocoders import GeoNames from geopy.geocoders import MapBox import api_credentials try: geolocator1 = Nominatim(user_agent=api_credentials.nominatim_agent) geolocator2 = GeoNames(username=api_credentials.geonames_user) geolocator3 = MapBox(api_key=api_credentials.mapbox_token) except: print("ERROR: FATAL: Unable to get geolocator") sys.exit() def getCountryInfo(lat, long): latitude = int(lat) longitude = int(long) lat_codes = latitude_dict[latitude] long_codes = longitude_dict[longitude] codes = lat_codes.intersection(long_codes) if len(codes) == 1: code = codes.pop() name = countries_dict[code] else: latlong = (lat, long) # get info from Nominatim
from geopy.geocoders import MapBox geolocator = MapBox( api_key= 'pk.eyJ1IjoiZGFuaWswNiIsImEiOiJjanJ3Yzg0czIwYWN3NDNvYWY3OGlxczNsIn0.Ri-3Ig44dA66UZY_evkW8g' ) file_read = open('resources/cities.list') file_write = open('resources/coordinates.list', 'w') i = 0 for i in range(0): file_read.__next__() # print(file_read.readline()) none_error = 0 name_error = 0 for line in file_read: try: location = geolocator.geocode(line) if location is None: print(None) none_error += 1 file_write.write(line + '\t' + 'error\tNone' + '\n') else: file_write.write(line + '\t' + str(location.latitude) + '\t' + str(location.longitude) + '\n') i += 1 except NameError as err: print(err)
import json from geopy.geocoders import MapBox geolocator = MapBox( api_key= "pk.eyJ1Ijoidm1hZGF0aGlsIiwiYSI6ImNra2FiNmw1aDAxNmIzMG5ha3NhZnE3N2YifQ.bWx-K-QAZYuJwWVjji6JmA" ) #path to json file rawfile = 'data_02-25-21' path = 'raw_data/' + rawfile featureCollectionAvali = {"type": "FeatureCollection", "features": []} featureCollectionExhaust = {"type": "FeatureCollection", "features": []} featureCollectionHubs = {"type": "FeatureCollection", "features": []} with open(path + '.json') as json_file: data = json.load(json_file) #print(data) #looping through each feature in the raw data for i in data['features']: #empty dictionary in GeoJSON Format feature = { "type": "Feature", "geometry": { "type": "Point",
def get(self, request): mapbox = MapBox( "pk.eyJ1IjoiaHVhbmdrYTk3IiwiYSI6ImNrMmw4c2V2YzA0bWUzZG83M2EzN2NjZ2wifQ.ICymOqR-bnQFjDcFtS3xCA") query = Story.objects.filter(approvalState="approved") geojson = {"type": "FeatureCollection", "features": []} location_queries = [] for story in query: loc = [] if story.city is not None and story.city != "": loc.append(story.city.replace(" ", "_")) if story.state is not None and story.state != "": loc.append(story.state.replace(" ", "_")) if story.country is not None and story.country != "": loc.append(story.country.replace(" ", "_")) location_queries.append(" ".join(loc)) for i, loc in enumerate(location_queries): feature = {"type": "Feature", "geometry": { "type": "Point" }, "properties": {}, "id": i} if Coordinates.objects.filter(coordquery=loc).count() == 0: try: code = mapbox.geocode(loc.replace("_", " ")) except: logger.info(loc) continue if code is None: continue lat = code.latitude lon = code.longitude Coordinates.objects.create( coordquery=loc, longitude=lon, latitude=lat) else: coords = Coordinates.objects.get(coordquery=loc) lat = coords.latitude lon = coords.longitude feature["geometry"]["coordinates"] = [lon, lat] loc_breakdown = loc.split() if len(loc_breakdown) > 0: feature["properties"]["city"] = loc_breakdown[0].replace( "_", " ") if len(loc_breakdown) > 1: feature["properties"]["state"] = loc_breakdown[1].replace( "_", " ") if len(loc_breakdown) > 2: feature["properties"]["country"] = loc_breakdown[2].replace( "_", " ") geojson["features"].append(feature) return http.JsonResponse(geojson)
import pandas as pd import sqlalchemy from sqlalchemy.ext.automap import automap_base from sqlalchemy.orm import Session from sqlalchemy import create_engine, func from geopy.geocoders import MapBox from geopy.distance import geodesic import pickle # Model setup #################################################################################################### geolocator = MapBox( api_key= "pk.eyJ1Ijoib2JuaWNob2xzb24iLCJhIjoiY2pwcHBrbmIxMGdhMTN4cWZ2czR6NDVwcCJ9.T5lnDc1uaxKgp4S18rFyBw", timeout=None) model_filename = 'ncaa_model.pkl' model_input_features = [ 'team_seed', 'team_travel_miles', 'opponent_seed', 'opponent_travel_miles', 'team_rank_SOS', 'team_rank_SRS', 'team_rank_ast', 'team_rank_blk', 'team_rank_fg', 'team_rank_fg2', 'team_rank_fg2_pct', 'team_rank_fg2a', 'team_rank_fg3', 'team_rank_fg3_pct', 'team_rank_fg3a', 'team_rank_fg_pct', 'team_rank_fga', 'team_rank_ft', 'team_rank_ft_pct', 'team_rank_fta', 'team_rank_pts', 'team_rank_pts_per_g', 'team_rank_stl', 'team_rank_trb', 'opponent_team_rank_SOS', 'opponent_team_rank_SRS', 'opponent_team_rank_ast', 'opponent_team_rank_blk', 'opponent_team_rank_fg', 'opponent_team_rank_fg2', 'opponent_team_rank_fg2_pct', 'opponent_team_rank_fg2a', 'opponent_team_rank_fg3', 'opponent_team_rank_fg3_pct',