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 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 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)
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') data = { 'timestamp': timey, 'latitude': location.latitude, 'longitude': location.longitude, "cost": total, 'type': typ } fname = "test.json" with open(fname, 'w') as s: json.dump(data, s)
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) name_error += 1 file_write.write(line + '\t' + 'error' + '\t' + str(err) + '\n') if i % 100 == 0: print(i)
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})