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)
Пример #2
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)
Пример #3
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)
Пример #4
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']
Пример #5
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']
Пример #6
0
def fill_departments():
    geocoder = Geocoder(
        access_token=
        'pk.eyJ1IjoibWVoZGliYWhhIiwiYSI6ImNrOGZ3bWdmMDAya24zZm8xbGJkYWw3cXkifQ.fS6Ny7_0bZ7swBKW7rvgEQ'
    )

    with open('departments.json') as json_file:
        departments = json.load(json_file)

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

    for f in departments['features']:
        f['properties']['amount'] = 0

    for l in locations:
        response = geocoder.reverse(lon=l['longitude'],
                                    lat=l['latitude'],
                                    types=['region'],
                                    limit=1).geojson()
        dep_code = response['features'][0]['properties']['short_code'].split(
            '-')[1]
        match = None
        for f in departments['features']:
            if f['properties']['code'] == dep_code:
                f['properties']['amount'] += float(l['amount'])

    with open("5-france.json", "w") as write_file:
        json.dump(departments, write_file)
Пример #7
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
Пример #8
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
Пример #9
0
def showResponse(jsonResponse):
    print "\n この場所はジオフェンスにあります"
    perm_geocoder = Geocoder()  # マップボックスの統合
    perm_geocoder.session.params['access_token'] = 'pk.eyJ1IjoiYnJhZHdib25uIiwiYSI6ImNqMjd3bmEwbjAwMjQyeHF0OGp3dm5ibWUifQ.uNds-BFopyeVQY7beRAeQw'
    for row in jsonResponse['rows']:
        try:
            response = perm_geocoder.reverse(
                lon=row['geometry']['coordinates'][0],
                lat=row['geometry']['coordinates'][1],
                types=['address','neighborhood','locality','place','region']
            )
        except:
            response = perm_geocoder.reverse(
                lon=row['geometry']['coordinates'][0][0][0],
                lat=row['geometry']['coordinates'][0][0][1],
                types=['address','neighborhood','locality','place','region']
            )
        try:
            address = response.geojson()['features'][0]['place_name']
        except:
            address = "場所は不明です"
        print " " + row['id'] + " " + address
        
    showMe = raw_input("\n JSONを見たいですか?(y/n) > ")
    if showMe == "y" or showMe == "Y":
        print "\n JSONレスポンス:"
        pprint(jsonResponse)
Пример #10
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)
Пример #11
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
Пример #12
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)
Пример #13
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")
Пример #14
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"
Пример #15
0
 def __init__(self, token, logger, service_params=None):
     service_params = service_params or {}
     self._token = token
     self._logger = logger
     self._geocoder_name = service_params.get(GEOCODER_NAME,
                                              DEFAULT_GEOCODER)
     self._geocoder = Geocoder(access_token=self._token,
                               name=self._geocoder_name)
Пример #16
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
Пример #17
0
def get_Postal_Address_Mapbox(longitude, latitude, api_key):
    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)
    response = geocoder.reverse(lon=longitude, lat=latitude)
    first = response.geojson()['features'][0]
    if response.status_code == 200:
        return first['place_name']
    else:
        return response.status_code
Пример #18
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
Пример #19
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)
Пример #20
0
def get_formatted_location(location_string):
    '''
    This function will provide a standard location based on google maps service
    online
    '''
    #Set up first the output
    output = {}
    output["raw"] = location_string
    mapbox_results = []
    #New code moving from google maps to MapBox.
    if (get_mapbox_key() is None) or (location_string == ""):
        #Data is not found, let's try removing some
        logging.warning(NO_VALID_KEY)
        return output
    else:
        try:
            mapbox_results = Geocoder(
                access_token=get_mapbox_key()).forward(location_string).json()
        except:
            #In case we have a problem with the key from mapbox or internet is down
            return output
    wrong_message = ("message" in mapbox_results.keys())
    if ((not wrong_message) and (len(mapbox_results) > 0)
            and (len(mapbox_results["features"]) > 0)
            and ("context" in mapbox_results["features"][0])):
        #Received data is ok, we can proceed
        output["latitude"] = mapbox_results["features"][0]["center"][1]
        output["longitude"] = mapbox_results["features"][0]["center"][0]
        for location_data in mapbox_results["features"][0]["context"]:
            if "locality" in location_data["id"]:
                output["city"] = location_data["text"]
            elif "place" in location_data["id"]:
                output["place_name"] = location_data["text"]
            elif "region" in location_data["id"]:
                output["county"] = location_data["text"]
            elif "country" in location_data["id"]:
                output["country"] = location_data["text"]
        #In the MapBox API apparently the more accurate location is at the beginning, to make sure overwrites any other
        place_type = mapbox_results["features"][0]["place_type"]
        place_text = mapbox_results["features"][0]["text"]
        if (place_type[0] in MAPBOX_TRANS_GENITOOLS.keys()):
            output[MAPBOX_TRANS_GENITOOLS[place_type[0]]] = place_text
        return output
    else:
        #Data is not found, let's try removing some
        logging.debug(NO_VALID_LOCATION)
        logging.debug(location_string)
        if (len(location_string.split(",")) > 3):
            output2 = get_formatted_location(",".join(
                location_string.split(",")[1:]))
            output2["raw"] = output["raw"]
            return output2
        else:
            return output
Пример #21
0
 def _initialize_services(self):
     '''Set the mapbox access token for both the StaticStyle API and Static API sessions'''
     self.service_style = StaticStyle(self.token)
     self.service_static = Static(self.token)
     self.service_geocoder = Geocoder()
     os.environ['MAPBOX_ACCESS_TOKEN'] = self.token
     self.service_style.session.params['access_token'] == os.environ[
         'MAPBOX_ACCESS_TOKEN']
     self.service_static.session.params['access_token'] == os.environ[
         'MAPBOX_ACCESS_TOKEN']
     self.service_geocoder.session.params['access_token'] == os.environ[
         'MAPBOX_ACCESS_TOKEN']
Пример #22
0
    def save(self, *args, **kwargs): 
        try:
            geocoder = Geocoder(access_token="pk.eyJ1IjoicHJhdGlrdmFpZHlhIiwiYSI6ImNrODZ2NzM1MDBpYXAzbm1ydDJyZm00dW0ifQ.B_iyhQhsrVLYbMMxLTNQ8Q").forward(self.address)
            response = geocoder.json()
            location = response['features'][0]
            self.lat = location['center'][0]
            self.lon = location['center'][1]
            self.address = location['place_name']
        except:
            pass

        super(ParkingSpot, self).save(*args, **kwargs) 
Пример #23
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)
Пример #24
0
    def __init__(self):
        # Public API. So commiting with code.

        self.access_token = "pk.eyJ1IjoiYXNobWFwNGdkIiwiYSI6ImNrOXBjb2k2dDA5YW4zb24xb3A2cWs5YXYifQ.3qtCEWPKAOEftYEEUDfDSQ"
        self.coder = Geocoder(access_token=self.access_token)
        self.cityDict = {}
        self.cityList = []
        self.processedBatch = []
        self.failed = []
        self.failed_ids = []
        self.failed_cities = []
        self.gaussian = []
        self._api = 0
Пример #25
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])
Пример #26
0
    def __init__(self):
        # Public API. So commiting with code. No big secret here.

#         self.access_token = "pk.eyJ1IjoiYXNobWFwNGdkIiwiYSI6ImNrOXBjb2k2dDA5YW4zb24xb3A2cWs5YXYifQ.3qtCEWPKAOEftYEEUDfDSQ"
        self.access_token = "pk.eyJ1IjoiYXNocm9uYXZvbmEiLCJhIjoiY2thYjRtY2hmMDkyeDJ0bzg0cHF5dTh5diJ9.10oEwG3nFpYrhYy-LufSuA"
        self.coder = Geocoder(access_token=self.access_token)
        self.cityDict = {}
        self.cityList = []
        self.processedBatch = []
        self.failed = []
        self.failed_ids = []
        self.failed_cities = []
        self.gaussian = []
        self._api = 0
Пример #27
0
def get_place(lat, lon):
    """Get the region name of the center lat/lon
    """
    geocoder = Geocoder()
    geocoder = Geocoder(access_token=os.environ['MapboxAccessToken'])
    place = 'Somewhere over the clouds!'
    try:
        response = geocoder.reverse(lon=lon, lat=lat, types=['region'])
        if response.status_code == 200:
            features = response.geojson()['features']
            place = features[0].get('place_name')
        return place
    except:
        return place
Пример #28
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)
Пример #29
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
Пример #30
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)
Пример #31
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)
Пример #32
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'
Пример #33
0
class GeoToolbox:
    _geocoder = None

    #constructor
    def __init__(self):
        self._geocoder = Geocoder(access_token = MAPBOX_TOKEN.MAPBOX_ACCESS_TOKEN)


    # get the address from lat and lon
    def getAddress(self, latitude, longitude):
        fullAnswer = {"status": False, "code" : None, "address": None}

        response = self._geocoder.reverse(lon = longitude, lat = latitude)

        fullAnswer["code"] = response.status_code

        if(response.status_code == 200):
            fullAnswer["status"] = True


            for f in response.geojson()['features']:
                fullAnswer["address"] = u'{place_name}'.format(**f)
                break


        return fullAnswer
Пример #34
0
 def __init__(self):
     self._geocoder = Geocoder(access_token = MAPBOX_TOKEN.MAPBOX_ACCESS_TOKEN)