<jupyter_start><jupyter_text>geoPy[read the docs](http://geopy.readthedocs.io/en/stable/)<jupyter_code># !pip install geopy<jupyter_output><empty_output><jupyter_text>Nominatim - Open Street Maphttps://wiki.openstreetmap.org/wiki/Nominatim<jupyter_code>from geopy.geocoders import Nominatim
geolocator = Nominatim()
location = geolocator.geocode("9, Singel, Amsterdam")
location.raw
location.address
(location.latitude, location.longitude)

location = geolocator.reverse("52.25, 4.99")
from geopy.geocoders import GoogleV3
geolocator = GoogleV3(format_string="%s, Netherlands")
address, (latitude, longitude) = geolocator.geocode("amsterdam")
address, latitude, longitude
from geopy.geocoders import GeoNames
geolocator = GeoNames(username='your_user_name_here', format_string="%s")
geolocator.geocode("Lutjebroek")
current_ip_location = !curl ipinfo.io/loc
latlon = current_ip_location[-1].split(',')
geolocator.reverse('{}, {}'.format(latlon[0], latlon[1]))
ip_location = !curl ipinfo.io
ip_location<jupyter_output><empty_output><jupyter_text>Here<jupyter_code>import json
import os
import platform
import re
import ssl
import subprocess
import requests
import urllib.request
from urllib.request import urlretrieve
import plistlib

from PIL import Image<jupyter_output><empty_output><jupyter_text>Credentials<jupyter_code>import os, pickle
pickle_file='../_credentials/here_credentials.pkl'
if not os.path.exists(pickle_file):
    Here={}
    Here['app_id'] = 'wL...9'
    Here['app_code'] = '9..._-A'
    with open(pickle_file, 'wb') as f:
        pickle.dump(Here, f)
else:
    Here=pickle.load(open(pickle_file,'rb'))<jupyter_output><empty_output><jupyter_text>GeoPy - geolocator<jupyter_code>from geopy.geocoders import Nominatim
geolocator = Nominatim()
location = geolocator.geocode("9, Singel, Amsterdam")
location.raw
location.address
(location.latitude, location.longitude)<jupyter_output><empty_output><jupyter_text>Search address<jupyter_code>def geo_address(api_url, searchtext):
    """Lookup address details as JSON
    Decode UTF-8 bytes to Unicode and convert single quotes to double quotes to make it valid JSON.
    Load the JSON to a Python list & dump it back out as formatted JSON."""
    
    http = '{}?app_id={}&app_code={}&searchtext={}'.format(api_url, Here['app_id'], Here['app_code'], searchtext)
    content = requests.get(http).content
    my_json = content.decode('utf8').replace("'", '"')
    data = json.loads(my_json)
    
    return data #json.dumps(data, indent=4, sort_keys=True)
def recursive_keys(json, values=False):
    """Recursively get keys and list items"""
    if type(json) == dict:
        for key, value in json.items():
            if values==False: value = ''
            if type(json[key]) == str: 
                print('--', key, ':',value)
                continue
            elif type(json[key]) == list: 
                print('list', key, ':', value)
                recursive_keys(json[key]) # [0]
            elif type(json[key]) == dict: 
                print('dict', key, ':', value)
                recursive_keys(json[key])

    elif type(json) == list:
        for i, item in enumerate(json):
            print(i, end=' ')
            recursive_keys(json[i])
api_url_places = 'https://geocoder.cit.api.here.com/6.2/geocode.json'
geo_bb = geo_address(api_url_places, '9, Singel, Amsterdam')
geo_bb
geo_address(api_url_places, '9, Singel, Amsterdam')['Response']['View'][0]['Result'][0]['Location']['NavigationPosition'][0]
recursive_keys(geo_bb)
def geo_location(api_url, payload):
    """Lookup address details as JSON
    Decode UTF-8 bytes to Unicode and convert single quotes to double quotes to make it valid JSON.
    Load the JSON to a Python list & dump it back out as formatted JSON."""

    http = '{}?app_id={}&app_code={}'.format(api_url, Here['app_id'], Here['app_code'])
    headers = {'Content-Type': 'application/json'}
    r = requests.post(http, data=json.dumps(payload), headers=headers)
    print(r.status_code, r.reason)
    my_json = r.content.decode('utf8').replace("'", '"')
    
    return json.loads(my_json)
api_url_locate = 'https://pos.cit.api.here.com/positioning/v1/locate'
payload = {
      "wlan": [{
      "mac": "36:68:95:1A:36:93",
      "powrx": -74}, {
      "mac": "18:64:72:B7:BC:B2",
      "powrx": -75}, {
      "mac": "18:64:72:B7:89:21",
      "powrx": -76}, {
      "mac": "18:64:72:B7:BC:B1",
      "powrx": -77}, {
      "mac": "18:64:72:B7:B1:63",
      "powrx": -79}] }

payload = {"wlan": [{"mac": "f4:0f:24:2e:2e:b3"},
                   {"mac": "10:41:7F:F4:0A:E9"}]}

payload = {"gsm": [{
              "mcc": 262,
              "mnc": 1,
              "lac": 5126,
              "cid": 21857}]}

loc_bb = geo_location(api_url_locate, payload)
loc_bb
def rev_geocoder(lat, lon):
    results = json.load(urllib.request.urlopen(
        '{}{},{},1000&mode=retrieveAddresses&maxResults=3&gen=8&app_id={}&app_code={}'.format(
            rev_geocoder_url, lat, lon, Here['app_id'], Here['app_code']), context=context)
                       )['Response']['View'][0]['Result']
    for result in results:
        if result['MatchQuality'].get('Street'):
            address = result['Location']['Address']['Label']
            break
        else:
            continue
    print('\nHERE location: {},{} ({})'.format(lat, lon, address))
    return address


def mia_cicular_picture(lon, lat, radius):
    mia_url = 'http://image.maps.api.here.com/mia/1.6/mapview?c={},{}&u={}&w=1280&h=1024' \
              '&app_id={}&app_code={}&t=3'.format(lat, lon, radius, Here['app_id'], Here['app_code'])
    picFileName = "miaPic.jpg"
    urlretrieve(mia_url, picFileName)
    Image.open(picFileName).show()


def wifi_positioning():
    try:
        if platform.system() == 'Windows':
            results = subprocess.check_output(["netsh", "wlan", "show", "network", "bssid"])
            results = results.decode("ascii")  # needed in python 3
            list = results.replace('\r', '').split('\n')
            mac_list = set()
            for element in list:
                if re.match('.*BSSID.*', element):
                    mac_list.add('{"mac": "' + (element.split(' : ')[1]) + '"}')
        elif platform.system() == 'Darwin':
            
            # GET WIFI list in XML format
            router_sniffer = '/System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources/airport -s -x'
            wifi_list = os.popen(router_sniffer).read()
            open('wifi_plist.txt', mode='w').write(wifi_list)
            # Convert XML to JSON/dict format
            hotspots_plist = plistlib.loads(str.encode(wifi_list), fmt=plistlib.FMT_XML)
#             print(hotspots_plist)
            mac_list = set()
            
            for hotspot in hotspots_plist:
#                 for key in hotspot.keys():
#                     print(hotspot['SSID_STR'], key, hotspot[key],'\n')
                ssid_str = hotspot['SSID_STR']
                bssid = hotspot['BSSID']
                rssi = hotspot['RSSI']
                if not re.findall('\w\w:\w\w:\w\w:\w\w:\w\w:\w\w', hotspot['BSSID']):
                    bssid_arr = bssid.split(':')
                    bssid_modified_arr = []
                    for bssid_elem in bssid_arr:
                        if len(bssid_elem) == 1:
                            bssid_elem = '0{}'.format(bssid_elem)
                        bssid_modified_arr.append(bssid_elem)
                    bssid = ':'.join(bssid_modified_arr)
                    
                print('SSID: {}, channel: {}, Mac:{}, signal: {}'.format(ssid_str, hotspot['CHANNEL'], bssid, rssi))
                
                mac_list.add('{\"mac\":\"' + bssid + '\", \"powrx\":' + str(rssi) + '}')  # BSSID + Powrx
            data = '\n{"wlan":[\n' + ',\n'.join(i for i in mac_list) + ']}'
            print('\nPOST request body:\n' + data)
            
            req = urllib.request.Request(url=positioning_url, data=data.encode('ascii'), headers=positioning_headers)
            json_result = json.loads(urllib.request.urlopen(req, context=context).read().decode('utf-8'))
            
            lat = json_result['location']['lat']
            lon = json_result['location']['lng']
            latlon = '{}, {}'.format(lat, lon)
            radius = json_result['location']['accuracy']
    except Exception:
        pass
        print('wifi positioning failed, getting ip location...')
        req = urllib.request.Request(url='http://ip-api.com/json')
        json_result = json.load((urllib.request.urlopen(req)))
        lat = json_result['lat']
        lon = json_result['lon']
        radius = 'N/A'
    mia_cicular_picture(lon, lat, radius)
    rev_geocoder(lat, lon)
    print('geoPy Nominatim location: ', geolocator.reverse(latlon))
    print('HERE lat, lon: {},{} radius: {} m'.format(lat, lon, radius))
    print('HERE Maps: https://wego.here.com/directions/mix/{},{}/?map={},{},15'.format(lat, lon, lat, lon))
    print('Google Maps: https://www.google.com.tw/maps/search/{},{}/@{},{},17z'.format(lat, lon, lat, lon))
    return lat, lon
context = ssl._create_unverified_context()
positioning_headers = {'Content-Type': 'application/json'}
positioning_url = 'https://pos.api.here.com/positioning/v1/locate?app_id={}&app_code={}'.format(Here['app_id'], Here['app_code'])
rev_geocoder_url = 'https://reverse.geocoder.api.here.com/6.2/reversegeocode.json?prox='
lat, lon = wifi_positioning()
latlon = '{}, {}'.format(lat, lon)
latlon
geolocator.reverse(latlon)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.16670152687722234, 'fraction_numerical': 0.015791675381719307, 'mean_word_length': 3.0265263157894737, 'pattern_counts': {'":': 23, '<': 25, '<?xml version=': 0, '>': 25, 'https://': 7, 'lorem ipsum': 0, 'www.': 1, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '6', 'dir': 'jupyter-structured-clean-dedup', 'id': '174203', 'license': 'MIT', 'n_tokens_mistral': 3365, 'n_tokens_neox': 3238, 'n_words': 592, 'path': 'geo_api_Here.ipynb', 'repo_name': 'aixpact/geo-location', 'size': '9562'}