Exemplo n.º 1
0
def directionRoute():
    if request.method == 'POST' or request.method == 'GET':
        data = request.get_json()
        src = data['start']
        dest = data['end']
        pro = data['profile']
        '''src=request.form['src']
                dest=request.form['dest']
                pro=request.form['pro']'''
        Profile = 'mapbox/' + pro
        PRofile = 'mapbox.' + pro
        MAPBOX_ACCESS_TOKEN = 'pk.eyJ1IjoidmluaXRoYS1zaHJlZSIsImEiOiJjamJ0ZW1yc24xMzB2Mnp1ZnVhazB6MnVzIn0.ynemM-bZ9mc4C9PuasnVow'
        geocoder = Geocoder(access_token=MAPBOX_ACCESS_TOKEN)
        #geocoder.session.params['access_token'] == 'sk.eyJ1IjoidmluaXRoYS1zaHJlZSIsImEiOiJjamNjMjkzZ3MwbTc0MndvMndtM2Ewb3lxIn0.cm3yhsou3E8UD0pm1GPKlA'
        geocode1 = geocoder.forward(src)
        src_geocode = geocode1.json()
        src1_geocode = json.dumps(src_geocode)
        geocode2 = geocoder.forward(dest)
        dest_geocode = geocode2.json()
        src_latlng = src_geocode["features"][0]['geometry']['coordinates']
        dest_latlng = dest_geocode['features'][0]['geometry']['coordinates']
        print(src_latlng)
        print(dest_latlng)
        origin = {
            'type': 'Feature',
            'properties': {
                'name': 'dummy'
            },
            'geometry': {
                'type': 'Point',
                'coordinates': [0, 0]
            }
        }
        origin['properties']['name'] = src
        origin['geometry']['coordinates'] = src_latlng
        destination = {
            'type': 'Feature',
            'properties': {
                'name': 'dummy'
            },
            'geometry': {
                'type': 'Point',
                'coordinates': [0, 0]
            }
        }
        destination['properties']['name'] = dest
        destination['geometry']['coordinates'] = dest_latlng
        print(origin)
        print(destination)
        services = Directions(access_token=MAPBOX_ACCESS_TOKEN)
        responses = services.directions([origin, destination], PRofile)
        directions_status = responses.status_code
        print(directions_status)
        directions_type = responses.headers['Content-Type']
        print(directions_type)
        directionResponse_json = responses.json()
        #print(directionResponse_json)
        return json.dumps(directionResponse_json)
    return "works bad"
Exemplo n.º 2
0
def output():

    #get the lat/long of origin and destination
    geocoder = Geocoder()
    geocoder.session.params['access_token'] = 'pk.eyJ1IjoiYWNiYXR0bGVzIiwiYSI6ImNrNXptdWtnajA4ZGYzamxscmR5ZmV4ZGEifQ.e99budVtY2MsprEhvTNEtQ'
    directions = Directions()
    directions.session.params['access_token'] = 'pk.eyJ1IjoiYWNiYXR0bGVzIiwiYSI6ImNrNXptdWtnajA4ZGYzamxscmR5ZmV4ZGEifQ.e99budVtY2MsprEhvTNEtQ'

    starting_location = request.args.get('starting_location')
    ending_location = request.args.get('ending_location')

    #Auto input, if fields left blank
    if starting_location == '':
        start_geo = geocoder.forward('200 E Colfax Ave, Denver, CO 80203')
    else:
        start_geo = geocoder.forward(starting_location)

    if ending_location == '':
        end_geo = geocoder.forward('7711 E Academy Blvd, 80230')
    else:
        end_geo = geocoder.forward(ending_location)
    
    origin = start_geo.geojson()['features'][0]
    destination = end_geo.geojson()['features'][0]

    route = directions.directions([origin,destination], 'mapbox/driving', alternatives=True, exclude = 'motorway')
    route1 = route.geojson()['features'][0]
    route2 = route.geojson()['features'][1]

    #makes a list of the start/end coordinates on each line segment of the route
    coord_points_alt1 = route1['geometry']['coordinates']
    coord_points_alt2 = route2['geometry']['coordinates']

    #get the coordinates for TURNS (at this point)
    intersections_df1 = geodb_query(coord_points_alt1)
    intersections_df2 = geodb_query(coord_points_alt2)

    #get the relative risk at each turn.
    total_risk1 = intersections_df1['Pred_Prob'].sum()
    total_risk2 = intersections_df2['Pred_Prob'].sum()

    
    if total_risk1 < total_risk2:
        best_route = route1
        next_route = route2
        risk_out_low = round(total_risk1,1)
        risk_out_high = round(total_risk2,1)
        
    else:
        best_route = route2
        next_route = route1
        risk_out_low = round(total_risk2,1)
        risk_out_high = round(total_risk1,1)
    
    risk_proportion = round(((1-(risk_out_low/risk_out_high))*100),1)

    return render_template("output.html", routeA = best_route, routeB = next_route, origin = origin, destination = destination,
    risk1 = risk_out_low, risk2 = risk_out_high, risk_proportion = risk_proportion)
Exemplo n.º 3
0
def mapbox_API(file):
    # importando o arquivo excel a ser utilizado
    book = load_workbook(
        file)  # abre o arquivo excel que será utilizado para cadastro
    sheet = book["Coordenadas"]  # seleciona a sheet chamada "Coordenadas"
    i = 2  # aqui indica começará da segunda linha do excel, ou seja, pulará o cabeçalho
    for r in sheet.rows:

        endereco = sheet[i][1]  # [linha][coluna]
        bairro = sheet[i][2]
        munic_UF = sheet[i][3]

        # Verifica se o campo 'Endereço' da primeira linha está preenchido
        if str(type(endereco.value)) == "<class 'NoneType'>":
            break

        # Concatena endereço completo com ou sem bairro preenchido
        if str(type(bairro.value)) == "<class 'NoneType'>":
            endereco_completo = endereco.value + " " + munic_UF.value
        else:
            endereco_completo = endereco.value + " " + bairro.value + " " + munic_UF.value

        # Iniciando Mapbox Geocoding API
        geocoder = Geocoder()
        geocoder = Geocoder(access_token=settings.MAPBOX_TOKEN)  # Token auth

        ## Buscando localização pela API pelo endereço completo
        # Busca pelo endereço completo no país Brasil, limitando a 3 resultados
        response = geocoder.forward(endereco_completo, country=['br'], limit=3)

        # Caso não localize o endereço, será informado na célula do excel
        if response.status_code == 401:
            sheet[i][6].value = "Nao foi possivel identificar"
            sheet[i][7].value = "NA"
            sheet[i][8].value = "NA"
            continue

        # Loop para coletar os 3 endereços/coordenadas
        k = 6
        for j in range(3):
            # Coletar o endereço completo
            address = response.geojson()['features'][j]['place_name']
            sheet[i][k].value = address

            # Coletar a latitude e logitude
            latlong = response.geojson()['features'][j]['center']
            latitude = latlong[1]
            longitude = latlong[0]

            # Preenchendo lat/long em cada célula
            sheet[i][k + 1].value = latitude
            sheet[i][k + 2].value = longitude

            k += 3

        i += 1

    file = book

    return file
Exemplo n.º 4
0
def get_coords(location):
    mapbox_api_key = config.mapbox_key
    geocoder = Geocoder(access_token=mapbox_api_key)
    response = geocoder.forward(location).json()
    center = response[u'features'][0][u'center']
    coords = (center[0], center[1])
    return coords
Exemplo n.º 5
0
def _get_lat_lon(location):
    geocoder = Geocoder(access_token=settings.MAPBOX_TOKEN)
    response = geocoder.forward(location)
    response.raise_for_status()
    longitude, latitude = response.geojson(
    )['features'][0]['geometry']['coordinates']
    return (latitude, longitude)
Exemplo n.º 6
0
def get_geodata(sheet, keys, countries=None):
    # in spreadsheet but not GeoJSON
    if not countries:
        countries = ['us', 'ca']
    geocoder = Geocoder()
    for key in keys:
        # San Jose, CA doesn't return results
        response = geocoder.forward(
            # special handling for key for actionnetwork events allows
            # for more than one event per locaion
            # make_key builds a compound key of <location>::<host>
            get_location_from_key(key).replace(', CA', ', California'),
            limit=1,
            country=countries).geojson()
        if 'features' in response and response['features']:
            feature = response['features'][0]
            log.info('geocode %s\n\t%s', key, feature)
            if feature['relevance'] < 0.75:
                log.warning('WARNING\terror geocoding %s', key)
                continue
            sheet[key]['geometry'] = response['features'][0]['geometry']
        else:
            if key in sheet:
                del sheet[key]
            log.warning('WARNING\terror geocoding %s', key)
Exemplo n.º 7
0
 def location_as_zip(self, zipcode, api_key):
     geocoder = Geocoder(access_token=api_key)
     response = geocoder.forward(zipcode, country=['us'])
     # Get Zipcode Center Latitude and Longitude from Mapbox
     self.city = response.json()['features'][0]['context'][0]['text']
     self.state = response.json()['features'][0]['context'][1]['text']
     self.coordinates = response.json()['features'][0]['center']
Exemplo n.º 8
0
def get_centre_point_lng_lat_for_address(address_string):
    geocoder = Geocoder()
    target_location_geocode = geocoder.forward(address_string)
    target_location_geocode_feature = target_location_geocode.geojson()['features'][0]

    # Returns list with coords in order lon, lat
    return target_location_geocode_feature['geometry']['coordinates']
Exemplo n.º 9
0
def geolocate_campaigns():
    geocoder = Geocoder(
        access_token=
        'pk.eyJ1IjoibWVoZGliYWhhIiwiYSI6ImNrOGZ3bWdmMDAya24zZm8xbGJkYWw3cXkifQ.fS6Ny7_0bZ7swBKW7rvgEQ'
    )

    with open('campaigns.csv', mode='r') as csv_file:
        csv_reader = list(csv.DictReader(csv_file, delimiter=';'))

    with open('locations.csv', 'w', newline='') as csvfile:
        writer = csv.writer(csvfile, delimiter=';')
        writer.writerow(['id', 'amount', 'number', 'longitude', 'latitude'])
        i = 1
        for row in csv_reader:
            if row.get('location1'):
                search = f"{row['location1']} {row['location2']} {row['location3']}"
                response = geocoder.forward(search, country=['fr'], limit=1)
                geojson = response.geojson()
                print(geojson)
                if geojson['features']:
                    writer.writerow([
                        i, row['amount'], row['number'],
                        geojson['features'][0]['center'][0],
                        geojson['features'][0]['center'][1]
                    ])
                    i += 1
def get_geodata(sheet, keys, location_fields, countries=None):
    # in spreadsheet but not GeoJSON
    countries = countries or ['us', 'ca']

    geocoder = Geocoder()
    for key in keys:
        row = sheet[key]
        location = ' '.join(
            map(lambda f: row['properties'][f].strip(), location_fields))
        location = row['properties'].get('street_address') or location
        resp = geocoder.forward(location, limit=1, types=['place', 'address'])
        response = resp.geojson()
        features = response.get('features')

        if not features or location.strip().lower() == 'address':
            if key in sheet:
                del sheet[key]
            log.error('Error geocoding no features %s: %s; %s', key, location,
                      resp.request.url)
            continue

        feature = features[0]
        log.info('geocode %s\n\t%s', location, feature)
        if feature['relevance'] < 0.75:
            log.error('Error geocoding relevance %s: %s', key, location)
            continue
        sheet[key]['geometry'] = feature['geometry']
        # 'place_name': '92646, Huntington Beach, California, United States'
        place_name = feature.get('place_name')
        if place_name:
            place_name = place_name.replace('%s, ' % key,
                                            '').replace(', United States', '')
            sheet[key]['properties']['placeName'] = place_name
    # rate limit is 10 per second, this stall keeps us within that
    time.sleep(0.1)
Exemplo n.º 11
0
def get_geodata(sheet, keys, countries=None):
    # in spreadsheet but not GeoJSON
    if not countries:
        countries = ['us', 'ca']
    geocoder = Geocoder()
    for key in keys:
        # San Jose, CA doesn't return results
        # special handling for key for actionnetwork events allows
        # for more than one event per locaion
        # make_key builds a compound key of <location>::<host>
        location = get_location_from_key(key).replace(', CA', ', California')
        response = geocoder.forward(location, limit=1,
                                    country=countries).geojson()
        if 'features' in response and response['features']:
            feature = response['features'][0]
            log.info('geocode %s\n\t%s', key, feature)
            if feature['relevance'] < 0.75:
                log.warning('Error geocoding %s', key)
                continue
            sheet[key]['geometry'] = feature['geometry']
            # 'place_name': '92646, Huntington Beach, California, United States'
            place_name = feature.get('place_name')
            if place_name:
                place_name = place_name.replace('%s, ' % location, '').\
                    replace(', United States', '')
                sheet[key]['properties']['placeName'] = place_name
        else:
            if key in sheet:
                del sheet[key]
            log.warning('Error geocoding %s', key)
Exemplo n.º 12
0
def filter_campsites():
    """Show list of all campsites"""

    campsites = Campsite.query.all()

    #User_id pulled from session
    user_id = session.get("user_id")
    user = User.query.filter_by(user_id=user_id).first()

    token = config.mapbox_access_token

    # Get form variables 
    region = request.form["state"]

    # Use mapbox API to fetch data
    # california_request = requests.get("https://api.mapbox.com/geocoding/v5/mapbox.places/" + region + ".json?access_token=pk.eyJ1IjoibG1pbGxlcjE2NSIsImEiOiJjazI0MXN6ZjIwNDNoM21tbmI4dnFobjMxIn0.Xf5-STNNUuVlsRZalbZrXA")
    geocoder = Geocoder()

    print("\n\n\n\n\n")
    response = geocoder.forward(region)
    response.status_code
    print("\n\n\n\n\n")
    print(response)
    response = response.json()
    print("\n\n\n\n\n")
    print(response)

    return redirect("/view-campsites")
Exemplo n.º 13
0
 def search(self, args, offset=0, limit=None, order=None, count=False):
     """
     Overring odoo's search function for custom search logic;
     Works for searches with "or" condition as well
     """
     res = []
     # If it's just a search of all elements
     if len(args) == 0:
         res = self._search(args, offset=offset, limit=limit, order=order,
                            count=count)
     # for multiple "or" search conditions
     search_phrases = [condition for condition in args if len(condition) > 1]
     for search_phrase in search_phrases:
         # Search in database
         temp_res = self._search([search_phrase], offset=offset, limit=limit,
                                 order=order, count=count)
         if not temp_res:
             # If no info in database, search it in mapbox
             geocoder = Geocoder(access_token="pk.eyJ1IjoiYW5hZWdvIiwiYSI6ImNrYW12YzMyeTE3eWUydHRkMndibGFyd3kifQ.At3CmGu9R8ZJS_Tpt9ngFQ")
             # geocoder = Geocoder(access_token=os.environ['MAPBOX_ACCESS_TOKEN'])
             response = geocoder.forward(search_phrase[2]).geojson()['features'][0]
             place_name = response["place_name"]
             coordinates = response["geometry"]["coordinates"]
             city = response["text"] if "place" in response["place_type"] else None
             country = response["text"] if "country" in response[
                 "place_type"] else None
             temp_res = [
                 self.create([{"place_name": place_name, "coordinates": coordinates,
                               "city": city, "country": country}]).id]
         # Append found database or mapbox info to the final result
         res += temp_res
     return res if count else self.browse(res)
Exemplo n.º 14
0
    def geo_mapbox(self, partner):
        # récupérer le token
        server_token = config.get("of_token_mapbox", "")
        if not server_token:
            raise UserError(u"MapBox n'est pas correctement configuré.")

        if partner._name == 'res.partner':
            addr_str = partner.get_addr_params()
        elif partner._name == 'of.geo.wizard.line':
            addr_str = partner.street_query
        else:
            addr_str = False

        if not addr_str:
            geocoding = 'no_address'
            geocodeur = ""
            latitud = 0
            longitud = 0
            precision = 'no_address'
            geocoding_response = ""
            street_response = ""
        else:
            # initialiser le geocodeur
            geocoder = Geocoder(access_token=server_token)
            geocodeur = 'mapbox'
            try:
                res = geocoder.forward(addr_str).json()
                self.mapbox_try += 1
            except Exception as e:
                return 'not_tried', "", 0, 0, 'not_tried', e, ""
            if not res or not res.get('features'):
                self.mapbox_fail += 1
                geocoding = 'failure'
                latitud = 0
                longitud = 0
                precision = "unknown"
                geocoding_response = ""
                street_response = ""
            else:
                res = res.get('features')[0]
                coords = res.get("center", [0, 0])
                latitud = coords[1]
                longitud = coords[0]
                score = res.get("relevance", 0)
                precision = CORRESPONDANCE_PRECISION_MAPBOX.get(res.get("place_type", ["other"])[-1], u"unknown")
                geocoding_response = json.dumps(res, indent=3, sort_keys=True, ensure_ascii=False)
                street_response = res.get("place_name", "")
                if score < 0.5 or latitud == 0 or longitud == 0:
                    self.mapbox_fail += 1
                    geocoding = 'failure'
                elif score < 0.7:
                    geocoding = 'need_verif'
                else:
                    geocoding = 'success_mapbox'
                    self.mapbox_success += 1

        return geocoding, geocodeur, latitud, longitud, precision, geocoding_response, street_response
Exemplo n.º 15
0
def request_geocoding(employee):
    geocoder = Geocoder()
    geocoder.session.params['access_token'] = app.config['MAPBOX_ACCESS_KEY']
    valid_types = list(geocoder.place_types.keys())
    valid_types.remove('address')
    valid_types.remove('country')
    country_code = None

    for index, city in enumerate(COUNTRY_KEYWORD_FILTER):
        if city in employee['location_text']:
            country_code = [COUNTRY_KEYWORD_FILTER[city]]

    if employee['name'] in IGNORE_POI:
        valid_types.remove('poi')
        valid_types.remove('poi.landmark')
        forward_response = geocoder.forward(employee['location_text'], types=valid_types, country=country_code)
    else:
        forward_response = geocoder.forward(employee['location_text'], types=valid_types, country=country_code)
    return forward_response
Exemplo n.º 16
0
def get_location_from_name(name):
    geocoder = Geocoder(access_token="pk.eyJ1IjoiY2xhaXJlZGVndWVsbGUiLCJhIjoiY2pnM3N1a3llMmF1azJxbnk3dm13dWptbCJ9.6T1hh6p4-bU-wrE-fVTSxQ")

    mapbox_response = geocoder.forward(name)
    if len(mapbox_response.geojson()['features']) == 0:
        return None

    location = mapbox_response.geojson()['features'][0]['geometry']

    return location
Exemplo n.º 17
0
def collect_trend(request):
    #try:
    api = setup()
    geocoder = Geocoder(
        access_token=
        "pk.eyJ1IjoibGFtb3R0YSIsImEiOiJjam1hdnJlaTIwcnh1M3Bqb2JzZjc5cnhvIn0.w986x6WriEojUaBUGQtMig"
    )

    trends = api.trends_place(id=request.POST.get('woeid'))

    lat = -22.3154
    long = -49.0615

    #trends[0] eh dicionario, ja que trends[] nao tem um indice [1], o [0] eh o unico que existe
    trendDict = trends[0]
    for key, value in trendDict.items():
        if key == 'locations':
            location = value[0].get('name')
            response = geocoder.forward(location)
            if response:
                features = response.geojson()['features'][0]
                long = features['geometry'].get('coordinates')[0]
                lat = features['geometry'].get('coordinates')[1]
        if key == 'trends':
            trendLista = value

            #Tomar cuidado ao mexer com as variaveis de trend, o retorno da API eh assim...
            #trends =
            #[{												--> Esse eh o {trendDict}
            #	key: 'value'								--> Exemplo do que key e value sao
            #	as_of: 'aaa',
            #	created_at: 'bbb',
            #	locations: [{ name: 'teste', woeid: 1 }],
            #	trends:										--> Esse eh o [trendLista]
            #	[
            #		{name: 'aaa', tweet_volume: 'bbb'},
            #		{name: 'aaa', tweet_volume: 'bbb'},
            #		{name: 'aaa', tweet_volume: 'bbb'}
            #	]
            #}]

    context = {
        'long': long,
        'lat': lat,
        'location': location,
        'dict': trendDict,
        'trends': trendLista,
        'query': request.POST.get('place_name')
    }

    #except KeyError:
    #	return render(request, 'tcc/error.html')
    #else:
    return render(request, 'tcc/trend_detail.html', context)
Exemplo n.º 18
0
 def getLatLng(self):
     # Check Cache
     key = 'geocode_query_1_' + self.query
     cache = r.get(key)
     if cache is None:
         geocoder = Geocoder()
         response = geocoder.forward(self.query)
         collection = response.json()['features'][0]['center']
         data = {"lat": collection[1], "lng": collection[0]}
         r.set(key, json.dumps(data))
         return data
     else:
         return json.loads(cache)
Exemplo n.º 19
0
    def geo_mapbox(self):
        # récupérer le token
        server_token = config.get("of_token_mapbox", "")
        if not server_token:
            raise UserError(u"MapBox n'est pas correctement configuré.")

        # initialiser le geocodeur
        geocoder = Geocoder(access_token=server_token)

        try:
            result = geocoder.forward(self.addr_search).json()
        except Exception:
            raise UserError(u"Une erreur inattendue est survenue lors de la requête")

        if not result or not result.get('features'):
            self.aucun_res = True
        else:
            line_ids_vals = [(5, )]
            for res in result.get('features', []):
                coords = res.get("center", {})
                for elem in res.get('context', []):
                    if elem.get("id", u"").startswith(u"postcode"):
                        res['zip'] = elem.get("text")
                    if elem.get("id", u"").startswith(u"place"):
                        res['city'] = elem.get("text")
                    if elem.get("id", u"").startswith(u"country"):
                        res['country'] = elem.get("text")
                if not coords:
                    continue
                vals = {
                    'geo_lat': coords[1],
                    'geo_lng': coords[0],
                    'geocodeur': 'mapbox',
                    'geocoding': 'success_mapbox',
                    'name': res.get("place_name", ""),
                    'street': '%s %s' % (res.get("address", u""), res.get("text", u"")),
                    'zip': res.get("zip", ""),
                    'city': res.get("city", ""),
                    'country': res.get("country", ""),
                    'score': res.get("relevance", 0),
                    'precision': CORRESPONDANCE_PRECISION_MAPBOX.get(res.get("place_type", ["other"])[-1], u"unknown"),
                    'geocoding_response': json.dumps(res, indent=3, sort_keys=True, ensure_ascii=False),
                }
                line_ids_vals.append((0, 0, vals))
            if len(line_ids_vals) == 1:
                self.aucun_res = True
            self.line_ids = line_ids_vals
            self.line_id = self.line_ids and self.line_ids[0] or False

        return True
Exemplo n.º 20
0
 def handle(self, *args, **options):
     geocoder = Geocoder(access_token=settings.MAPBOX['access_token'])
     for id in options['id']:
         poi = POI.objects.get(pk=id)
         rep = geocoder.forward(poi.address)
         if rep.status_code == 200:
             geojson = rep.geojson()
             try:
                 f = geojson['features'][0]
                 poi.place = f['place_name']
                 poi.longitude = f['center'][0]
                 poi.latitude = f['center'][1]
             except:
                 print(geojson)
Exemplo n.º 21
0
def mapbox_geocoder_fw(address):
    """
    address (str): 
    return (float, float): longitude, latitude
    """
    geocoder = Geocoder()
    # TODO: add some proximity (from the user)?
    response = geocoder.forward(address)

    r = response.json()
    logging.debug("Rettrieved potential locations for %s: %s", address, r)

    coord = r["features"][0]['center']
    return float(coord[0]), float(coord[1])
Exemplo n.º 22
0
def map():

    page_link = request.args.get('url')

    # here, we fetch the content from the url, using the requests library
    page_response = requests.get(page_link, timeout=5)

    #we use the html parser to parse the url content and store it in a variable.
    soup = BeautifulSoup(page_response.content, "html.parser")

    # print(soup)

    out = soup.find_all(text=re.compile("^([^,]+),\s(AL|AK|AS|AZ|AR|CA|CO|CT|DE|DC|FM|FL|GA|GU|HI|ID|IL|IN|IA|KS|KY|LA|ME|MH|MD|MA|MI|MN|MS|MO|MT|NE|NV|NH|NJ|NM|NY|NC|ND|MP|OH|OK|OR|PW|PA|PR|RI|SC|SD|TN|TX|UT|VT|VI|VA|WA|WV|WI|WY)(?:(\s\d{5}))?$"))

    if out == []:
        out = soup.find_all(text=re.compile("(?:,)([^,]+),\s(AL|AK|AS|AZ|AR|CA|CO|CT|DE|DC|FM|FL|GA|GU|HI|ID|IL|IN|IA|KS|KY|LA|ME|MH|MD|MA|MI|MN|MS|MO|MT|NE|NV|NH|NJ|NM|NY|NC|ND|MP|OH|OK|OR|PW|PA|PR|RI|SC|SD|TN|TX|UT|VT|VI|VA|WA|WV|WI|WY)\s(?:(\d{5}))?"))  


    # for debugging
    # print("\n\n\n\n\n\n\nOUTPUT")
    # print(out)

    # Can comment out these lines and uncomment last lines 
    # to dummy out geocode call and save API quota

    geocoder = Geocoder(access_token=mapbox)

    for_plotting = []

    for place in out:

        response = geocoder.forward(place, 
                                    limit = 1, 
                                    country=['us']) 
                                    # types=['place'])

        first = response.geojson()['features'][0]
        # print(first['place_name'])
        # print(first['geometry']['coordinates'])

        for_plotting.append([first['place_name'], first['geometry']['coordinates']])


    # Uncomment these lines to dummy out API call and save quota

    # for_plotting = [['1105 Hainesport Mount Laurel Rd, Mount Laurel, New Jersey 08054, United States',
    #           [-74.87109, 39.95182]]]

    return render_template('map.html', mapbox = mapbox, places=for_plotting, link=page_link)
Exemplo n.º 23
0
	def save_model(self, request, obj, form, change):
		from mapbox import Geocoder
		import json

		name = "{0}, {1}".format(form.cleaned_data['name'], form.cleaned_data['country'].name)
		geocoder = Geocoder(access_token=BaseSettings.objects.get(pk=1).mapbox_access_key)
		response = geocoder.forward(name)
		mapbox_coords = response.json()['features'][0]['center']

		coordinates = Coordinates.objects.create(longitude=mapbox_coords[0], latitude=mapbox_coords[1])
		coordinates.save()

		obj.coordinates = coordinates

		super(CityAdmin, self).save_model(request, obj, form, change)
Exemplo n.º 24
0
def geocode(address):
    g = Geocoder(access_token=mapbox_access_token)
    try:
        print address
        response = g.forward(address, country=['in'])
        collections = response.json()
    except:
        print 'Error Occurred'
        return "Not Found", 'Not Found'
    else:
        if response.status_code == 200 and len(collections['features']) >= 1:
            lat, lng = collections['features'][0]['geometry']['coordinates']
            return lat, lng
        else:
            return 'Not Found', 'Not Found'
Exemplo n.º 25
0
def geocode():
    if request.method == 'POST' or request.method == 'GET':
        #place=request.form['place']
        data = request.get_json()
        place = data['place']
        MAPBOX_ACCESS_TOKEN = 'pk.eyJ1IjoidmluaXRoYS1zaHJlZSIsImEiOiJjamJ0ZW1yc24xMzB2Mnp1ZnVhazB6MnVzIn0.ynemM-bZ9mc4C9PuasnVow'
        geocoder = Geocoder(access_token=MAPBOX_ACCESS_TOKEN)
        #geocoder.session.params['access_token'] =='pk.eyJ1IjoidmluaXRoYS1zaHJlZSIsImEiOiJjamJ0ZW1yc24xMzB2Mnp1ZnVhazB6MnVzIn0.ynemM-bZ9mc4C9PuasnVow'
        geocode1 = geocoder.forward(place)
        print(geocode1.status_code)
        geocode = geocode1.json()
        sorted(geocode.keys())
        print(geocode)
        return json.dumps(geocode)
    return "bad request"
Exemplo n.º 26
0
def main():

    geocoder = Geocoder()

    for i in range(1, 6):
        pathSimple = "D:/Spatial/Data/CSV/Rental_Data/CSV/simple/b" + str(
            i) + "_condo_comp012816.txt"
        pathReworked = "D:/Spatial/Data/CSV/Rental_Data/CSV/reworked_mapbox/b" + str(
            i) + "_reworked.txt"
        with open(pathSimple, 'r') as old_file:
            with open(pathReworked, 'w') as new_file:
                for line in old_file:
                    temp = line.split("\t")
                    temp = temp[0] + ", " + " New York"
                    response = geocoder.forward(temp,
                                                lon=-73.935242,
                                                lat=40.730610)
                    first = response.geojson()['features'][0]
                    if response.status_code == 200:
                        WriteMyLine(first, new_file, line)
                    else:
                        print(response.status_code + " -> warten")
                        time.sleep(65)
                        response = geocoder.forward(temp,
                                                    lon=-73.935242,
                                                    lat=40.730610)
                        if response.status_code == 200:
                            first = response.geojson()['features'][0]
                            WriteMyLine(first, new_file, line)
                            print("geklappt")
                            time.sleep(3)
                        else:
                            print("nochma Fail")
                            exit()

    print("Finished")
Exemplo n.º 27
0
def create_pharma(request):
    if request.method == 'POST':  # When we POST the form.
        form = PharmacyForm(request.POST)
        if form.is_valid():  # Check if the form is valid.
            user = request.session['username']  # Get the username.
            form.save(user)

            name = form.cleaned_data.get('name')
            address = form.cleaned_data.get('address')
            phone_number = form.cleaned_data.get('phone_number')

            pharmacy = Pharmacy.objects.get(name=name)
            pk = pharmacy.pk
            geocoder = Geocoder(
                access_token=mapbox_access_token
            )  # Use a geocoder to turn the address into coordinates.
            response = geocoder.forward(address)
            first = response.geojson()['features'][0]
            coords = [
                round(coord, 2)  # Get the coords from the JSON response.
                for coord in first['geometry']['coordinates']
            ]
            new_location = '{ "type": "Feature", "geometry": { "type": "Point", "coordinates": ' + str(
                coords
            ) + '}, "properties": { "title": "' + name + '", "description": "' + str(
                pk) + '"}}'
            new_location = json.loads(
                new_location)  # Add the new location to the GeoJSON data.

            file_path = os.path.join(settings.BASE_DIR,
                                     'pharma_locations.json')

            pharma_locations = open(file_path)
            with pharma_locations as data_file:
                data = json.load(data_file)

            data["features"].append(new_location)

            pharma_locations = open(file_path, 'w')  # Write the new file.
            with pharma_locations as outfile:
                json.dump(data, outfile)

            return redirect(
                'phone_verification'
            )  # After registering a pharmacy, they still have to verify their phonenumber.
    else:
        form = PharmacyForm()
    return render(request, 'pharmacies/create_pharmacy.html', {'form': form})
Exemplo n.º 28
0
def get_GPS_Coordinates_Mapbox(street, city, api_key):
    # print(street, file=sys.stderr)
    # print(api_key, file=sys.stderr)
    endpoint_full = "mapbox.places-permanent"  # utilisé pour des fonctions avancées payantes (on n'utilise pas!)
    endpoint = "mapbox.places"
    geocoder = Geocoder(access_token=api_key)
    postal_address = street + " " + city
    response = geocoder.forward(postal_address)
    # print(response,file=sys.stderr)
    # print(postal_address,file=sys.stderr)
    debug = response.geojson()
    # print(debug,file=sys.stderr)
    first = response.geojson()['features'][0]
    if response.status_code == 200:
        return [round(coord, 5) for coord in first['geometry']['coordinates']]
    else:
        return response.status_code
Exemplo n.º 29
0
def update_location_submit(request, biz_id, loc_id):
    if request.method == 'POST':
        # use forms.py to validate form data
        form = NewLocation(request.POST)
        if form.is_valid():
            # form data is valid
            business = get_object_or_404(Business,
                                         id=biz_id)  # Get business object

            geocoder = Geocoder(access_token=MAPBOX_KEY)  # Gather geocode data
            response = geocoder.forward(
                address=form.cleaned_data['street'] \
                    + " " + form.cleaned_data['city'] \
                    + " " + form.cleaned_data['state'] \
                    + " " + form.cleaned_data['zipcode'],
                limit=1
            )
            features = response.geojson()['features'][0]

            location = get_object_or_404(
                Location, id=loc_id)  # Get location object to update
            location.name = form.cleaned_data[
                'name']  # Update attributes with form data
            location.business = business
            location.is_primary = form.cleaned_data['is_primary']
            location.street = form.cleaned_data['street']
            location.city = form.cleaned_data['city']
            location.state = form.cleaned_data['state']
            location.zipcode = form.cleaned_data['zipcode']
            location.longitude = features["geometry"]["coordinates"][0]
            location.latitude = features["geometry"]["coordinates"][1]
            location.neighborhood = features["context"][0]["text"]
            location.phone = form.cleaned_data['phone']

            location.save()
            return redirect(reverse('business:get_all'))
        else:
            # form data has validation errors
            print "ERRORS"
            request.session['form_errors'] = form.errors
    return redirect(reverse('business:add_location', kwargs={'id': id}))
Exemplo n.º 30
0
def collect_user(request):
    try:
        api = setup()
        geocoder = Geocoder(
            access_token=
            "pk.eyJ1IjoibGFtb3R0YSIsImEiOiJjam1hdnJlaTIwcnh1M3Bqb2JzZjc5cnhvIn0.w986x6WriEojUaBUGQtMig"
        )

        user_data = api.get_user(request.POST.get('user_name'))
        user_favourites = api.favorites(id=request.POST.get('user_name'))
        tweets = api.user_timeline(screen_name=request.POST.get('user_name'),
                                   count=20,
                                   tweet_mode="extended")

        location = user_data.location

        lat = -22.3154
        long = -49.0615

        response = geocoder.forward(location)
        if response:
            features = response.geojson()['features'][0]
            long = features['geometry'].get('coordinates')[0]
            lat = features['geometry'].get('coordinates')[1]

        context = {
            'lat': lat,
            'long': long,
            'user_data': user_data,
            'user_favourites': user_favourites,
            'tweets': tweets,
            'query': request.POST.get('user_name'),
        }

    except tweepy.TweepError:
        return render(request, 'tcc/user_protected.html')
    #except KeyError:
    #	return render(request, 'tcc/error.html')
    else:
        return render(request, 'tcc/user_detail.html', context)
Exemplo n.º 31
0
def home():
    mapbox_access_token = 'pk.eyJ1IjoibWF0dG9mZmljZSIsImEiOiJjazlqdHYwZ2kwMHBxM2xscmF5bzdpc2dsIn0.iDUw71WZCer5ZrbOkEusqg'
    name = None
    current_location = 'Algernon Terrace'
    coords = [-1.435385, 55.019037]
    starting_coords = coords
    desired_location = ''
    form = NameForm()

    if form.validate_on_submit():
        user = User.query.filter_by(username=form.name.data).first()
        name = form.name.data
        current_location = form.current_location.data
        desired_location = form.desired_location.data
        geocoder = Geocoder(
            access_token=
            "pk.eyJ1IjoibWF0dG9mZmljZSIsImEiOiJjazlqdHYwZ2kwMHBxM2xscmF5bzdpc2dsIn0.iDUw71WZCer5ZrbOkEusqg"
        )
        coords = geocoder.forward(
            desired_location).json()['features'][0]['geometry']['coordinates']
        if user is None:
            user = User(username=form.name.data,
                        currentLocation=current_location)
            db.session.add(user)

            db.session.commit()
        session['name'] = name
        session['current_location'] = current_location
        current_location = session['current_location']
        form.name.data = ''
        form.current_location.data = ''
        form.desired_location.data = ''
    return render_template('home.html',
                           form=form,
                           name=session.get('name'),
                           starting_coords=starting_coords,
                           desired_location=desired_location,
                           current_location=current_location,
                           coords=coords,
                           mapbox_access_token=mapbox_access_token)