Имея учётную запись в Yandex и Google, можно получить ключ для доступа к API сервисов геолокации. Что с ними делать далее в замтке.
На сервере, к имени которого привязан ключ, размещаем скрипт следующего содержания:
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright ©2017 Aleksey Rogovimport requests import json import xml.dom.minidom import cgi import time import sqlite3 keys = ('v_2dzKmERdfe6Q0GRK4CIQ8sR9Ba6iPiQ-5XAPrjFLt7AuF0', '5VbeulhlZ-R-nTlHmv5hX3hrwgB3AqwrBT801p50x2NAB7Y_', 'nSlKdUzNCTDTHEFOCwtrzfo7S1GHuPMPa1AIUSO1ZcoqDqM7') yandex_api_key = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx=='; yandex_api_url = 'http://api.lbs.yandex.net/geolocation'; google_api_key = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx-xxxxx'; google_api_url = "https://www.googleapis.com/geolocation/v1/geolocate?key=" + google_api_key; dbname = 'geoapi.sqlite' params = cgi.FieldStorage() key = params.getfirst('key') provider = params.getfirst('provider') mcc = params.getfirst('mcc') mnc = params.getfirst('mnc') lac = params.getfirst('lac') cellid = params.getfirst('cellid') signal = params.getfirst('signal') print('Content-type: text/html',end='\r\n\r\n') if not key or not provider or not mcc or not mnc or not lac or not cellid or not signal: print('{"status":false,"reason":"arguments missmatch","lat":0,"lng":0,"precision":0,"url":""}') exit() if key not in keys: print('{"status": false,"reason":"invalid key"}') exit() if not mcc.isdigit() or not mnc.isdigit(): print('{"status":false,"reason":"invalid format"}') exit() input_xml = '''xml= '''%(yandex_api_key, mcc, mnc, cellid, lac, signal) input_json='''{ "homeMobileCountryCode": %s, "homeMobileNetworkCode": %d, "radioType": "gsm", "carrier": "BEELINE", "considerIp": "false", "cellTowers": [ { "cellId": %d, "locationAreaCode": %d, "mobileCountryCode": %s, "mobileNetworkCode": %d, "age": 0, "signalStrength": %s, "timingAdvance": 15 } ] }'''%(mcc, int(mnc), int(cellid, 16), int(lac, 16), mcc, int(mnc), signal) if provider == 'yandex': api_url = yandex_api_url header = {'Content-type': 'application/x-www-form-urlencode'} body = input_xml elif provider == 'google': api_url = google_api_url header = {'Content-Type': 'application/json'} body = input_json r = requests.post(api_url, headers=header, data=body) if not r: print('{"status":true,"reason":"provider error"}') exit() lat = 0 lon = 0 prec = 0 alt = 0 altprec = 0 if provider == 'yandex': xml = xml.dom.minidom.parseString(r.text) xml.normalize() lat = xml.getElementsByTagName('latitude')[0].childNodes[0].nodeValue lon = xml.getElementsByTagName('longitude')[0].childNodes[0].nodeValue prec = xml.getElementsByTagName('precision')[0].childNodes[0].nodeValue alt = xml.getElementsByTagName('altitude')[0].childNodes[0].nodeValue altprec = xml.getElementsByTagName('altitude_precision')[0].childNodes[0].nodeValue print('{"status":true,"lat":' + str(lat) + ',"lng":' + str(lon) + ',"precision":' + str(prec).split('.')[0] + ',"url":"https:\/\/maps.yandex.ru\/?ll=' + str(lon) + ',' + str(lat) + '&pt=' + str(lon) + ',' + str(lat) + '&spn=0.05,0.05&l=sat,skl' + '"}') elif provider == 'google': jsn = json.loads(r.text) lat = jsn['location']['lat'] lon = jsn['location']['lng'] prec = jsn['accuracy'] print('{"status":true,"lat":' + str(lat) + ',"lng":' + str(lon) + ',"precision":' + str(prec).split('.')[0] + ',"url":"https:\/\/www.google.ru\/maps\/@' + str(lat) + ',' + str(lon) + ',15z?hl=ru"}') tnow = int(time.time()) conn = sqlite3.connect(dbname) cur = conn.cursor() cur.execute('INSERT INTO geoapi VALUES(NULL,?,?,?,?,?,?,?,?,?)',(str(tnow),str(mcc),str(mnc),str(lac),str(cellid),str(lat),str(lon),str(alt),str(prec))) conn.commit() conn.close() 1.0 %s | %s %s %s %s %s 1000
переменным yandex_api_key и google_api_key нужно прописать соответствующие ключи доступа, в переменную keys — ключи клиентов.
Для определения координат нужно сделать следующий GET-запрос: https://mysite/geoapi?key=apikey&provider=yandex&mcc=250&mnc=99&lac=220000&cellid=330000&signal=-81, меняя переменную provider, можно выбрать поставщика услуг геолокации. В ответ сервер вернёт JSON-объект с данными о местоположении:
{"status":true,"lat":XX.XXXXXXX,"lng":YY.YYYYYYY,"precision":3201,"url":"https:\/\/maps.yandex.ru\/?ll=YY.YYYYYYY,XX.XXXXXXX&pt=YY.YYYYYYY,XX.XXXXXXX&spn=0.05,0.05&l=sat,skl"}