Notice since 2024,
applications with insufficient configuration details will have national geographic information public service platform application programming interface access restricted.
it recommends naming method is (application name)-(application scenario).
steps
visit lbs.tianditu.gov.cn
console
create a new application(cloud-based)
select the application type(server)
one of the web service application programming interfaces is reverse geocoding(transform geographic coordinates into structured address data)
example
http://api.tiantitu.gov.cn/geocoder?postStr={'lon':x coordinate,'lat':y coordinate,'ver':interface version}&type=geocode&tk=keyname
need to use
import requests r=requests.request('GET',url)parameters 'GET' method,or use mozilla's headless mode
we can check the response status code
r.status_code
it must be 200
r.json
a method not a attribute
r.json()['msg']
parameter msg meaning is there any response information.
parameter type(string)('ok':it has information) is must be 'ok'
r.json()['result']
specific information of the response
r.json()['result']['formatted_address']
detailed address
But baidu map open platform,
student version:
need to fill in your real name,mobile phone number,
enter your school name,enter in your major,
select graduation date,
fill in your identification card number,authentication address,usage scenario,upload student identification photo;
developer registration:
fill in your real name,mobile phone number,
enter your real company name,business license number,email address,upload certficates photo to verify business information.
can only use https://lbsyun.baidu.com/jsdemo/demo/yLngLatLocation.htm
Step:
visit china telecom intelligent gateway,
confirm login
network side information
ipv4 information
ip address
from geoip2 import database import sys def yLngLatLocation(IP): r=database.Reader('./GeoLite2-City.mmdb').city(IP).location print(f"{r.longtitude}\t{r.latitude}") if __name__=="__main__": yLngLatLocation(sys.argv[1])download city database:
create new license
key
confirm
visit
https://download.maxmind.com/geoip/databases/GeoLite2-City/download?suffix=tar.gz
fill in username as account id,fill in password as license key;or csv format.
pandas use IO tools to read data from csv file into DataFrame,
read_csv parameters:
usecols:list or function,
nrows:int.
example:
usecols=['network','latitude','longtitude']
csv file downloaded in 2025/4/25 was 1048576 of rows.
encoding:encode,string,example:
encoding='utf-8'
filepath:"./GeoLite2-City-Blocks-IPv4.csv"
ipaddress.IPv4Address
will construct ipv4 address,if address is not valid,will raise AddressValueError
.
if address is private,then ipaddress.IPv4Address(string).is_private
is True
ipv4 address is 32-bit,subnet mask is also 32-bit.
list(ipaddress.IPv4Network(string).hosts()) is a list of all available hosts,in addition to the network address(ex. 192.168.1.0) or broadcast address(ex. 192.168.1.255)(see RFC4632 page 7)
and string.split('.')[0]
,record as lambda function f,is network identifier of string.
take class C and china telecom intelligent gateway as example,subnet mask is 255.255.255.0,use CIDR notation is 192.168.1.1/24,all the network identifier of string in the list is 192.
values attribute of DataFrames object will return numpy array b.
j in range(1048576);e in range(1048576)
,among them b[j][0]
is network segment,b[j][2]
is longtitude,b[j][1]
is latitude.
k=list(b)
,e is natural number that satifies f(k[e][0])==f(string)
if 'e' not in vars(),then network identifier must greater than 69(because you click "sign up for an account with no obligation to purchase or use our products."),as for why,leave it for thought.
recommend replacing range(start,stop)
with ProgressBar(widgets=[Percentage(),Bar('█')])(range(start,stop)).
Web application programming interface:
the getCurrentPosition()
method of the Geolocation interface is used to get the current position of the device,this feature is available only in secure contexts.
if a page's context is secure,then window.isSecureContext
must be true
.
parameters:
callback function sxsymxsyy,
optional callback function E,
optional object.
<button onclick="YZL()">click event</button> <!--a clickable button,embed javascript code.--> function YZL(r) { navigator.geolocation.getCurrentPosition(function sxsymxsyy(r) {const c = r.coords.latitude[return latitude] + "\n" + r.coords.longitude[return longtitude] + "\n" + r.coords.accuracy[return less or more(meters)];document.write(c)}, function E(e) {console.error(e)[error log];}, {enableHighAccuracy: true[provide a more accurate position.]}); }
Ralated php:
http_response_code(500);
will raise this page isn't working right now error in microsoft edge.
$_SERVER
is an array containing information such as HTTP_USER_AGENT,REMOTE_ADDR
$HTTP_RAW_POST_DATA
deprecated in the version 8.(and must write php.ini),it can be replaced by $d=file_get_contents('php://input');
then use json_decode($d,true)
decode it,return an array.if array does not contain 'longtitude' key or 'latitude' key or 'accuracy' key and their value,then raise 400 error,because the client's request syntax is wrong.
JSON.stringify
method turn
{ longtitude: (float).toFixed(number), latitude: (float).toFixed(number), accuracy: (float).toFixed(number) }into a json string,similar to
json.dumps
.
I use fetch application interface to send post request,
Content-Type
in header is application/json
,the field is MIME(media type),if you are interested in it,go and see xiaopan123's video(have you ever thought about uploading something else where you upload?)
when the
json.status
is true,use document.getElementById
method return
a element whose id matches the 'studentid',
and set it to insert_id
(you need understand AUTO_INCREMENT
in Mysql first.)INSERT address(longtitude,latitude,accuracy)
will insert the newly created row into the existing table "address",
VALUES(?,?,?)
,question mark is placeholder among them;
with it,I need to use
bind_param
bind parameter as variable to it.
and one of
bind_param
's parameter types is 'ddd',becuase longtitude,latitude,accuracy(three),all of them are float.
if there is no
execute
,then raise 500 error,becuase there must be a server error.In any cause,then connection will close.
if client access the file directly(the payload in name in network in developer tool does not exist.)
will raise 405 error,because I forbid the request that use get method.
example:
header('Content-Type: application/json');send raw http header,make browser display pretty-print checkbox.
echo json_encode(["status"=>false,"msg"=>"405 Method Not Allowed"]);so far,I use front end to request json data from back end ,use back end to write database,basiclly completed.
Then can load mod_rewrite in httpd.conf,create new file .htaccess in web root directory.
Write RewriteEngine On
to enable rewrite
RewriteCond %{HTTP_REFERER} !^http://XXX\.XXX\.XXX\.XXX:port/webpage.html [NC] RewriteRule "\.js" "-" [F,NC]square brackets indicate sign,split by ','.
NC indicate case insensitivity,define rewrite condition as
HTTP_REFERER
in http header.
visit js directly will raise 403 error.and write in php:
header("Access-Control-Allow-Origin: http://XXX.XXX.XXX.XXX:port")
specify that all files with js extensions should not be shared with the specified origin(except local).
then use
<script src='filename.js'></script>
,no button require.at last,
step:
windows:
display settings,privacy and security,location, turn location services on;
android:
settings,location,use location;
apps,permissions,location,allow only while using the app.then open website.
Haversine formula can calculate the geodesic distance between two points on a sphere.
the folling is latex:
$g=\sin{((c-a)/2)}^{2}+\cos{b}\cdot\cos{d}\cdot\sin{((d-b)/2)}^{2}$ $2\cdot r\cdot \arctan{\cfrac{\sqrt{g}}{\sqrt{1-g}}}$ $2\cdot r\cdot \arcsin{\sqrt{g}}$a,c longtitude(float)
b,d latitude(float)
a,b,c,d=(math.radians(j) for j in [a,b,c,d])
,or use map
.
return the geodesic distance between two points on earth.
r:earth's radius 6371km.(unit km) or
from geopy import distance distance.distance(point,point)
posted May 13,2025 8:59 PM