首页 > 其他分享 >经纬度转省市名称

经纬度转省市名称

时间:2023-02-04 14:33:59浏览次数:59  
标签:multi 省市 mongo 经纬度 db name 名称 geo polygon

移动端采集到经纬度,需要按照经纬度转换为省市。

高德有提供相应的 API,这个是非常推荐的一种方式,但是提高限额和并发量的价格偏高,其次基本只在国内可用,国内企业可以考虑。

还有一种方式是自己收集省市区的数据,整理为相应的边界数据,然后通过边界数据自行查询。

实现

GitHub AreaCity-JsSpider-StatsGov 上面有全国省市区的边界数据,而且更新比较及时,down 下来,解析一下塞进 Mongo 里

import csv
import sys

from pymongo import MongoClient

csv.field_size_limit(sys.maxsize)
csv_location = 'resource/geo.csv'

mongo_svr = 'mongodb://root:xjJYhsgujRTXapIl@localhost:27017'
mongo_db = 'geo'
mongo_db_collection = 'city_polygon'


def load_geo(location):
    with open(location, newline='', mode='r', encoding='utf-8-sig') as cf:
        reader = csv.reader(cf)
        for row in reader:
            yield row


def load_mongo_collection():
    client = MongoClient(mongo_svr)
    return client[mongo_db][mongo_db_collection]


if __name__ == '__main__':
    collection = load_mongo_collection()
    count = 0
    for r in load_geo(csv_location):
        count += 1
        if count == 1:
            continue
        deep = r[2]
        name = r[4].split(' ')
        print('At row: ' + str(count) + ', name: ' + ','.join(name) + ', deep: ' + deep)
        if deep == '1':
            geo = r[5].split(' ')
            multi_polygon = []
            for ele in r[6].split(';'):
                polygon = [list(map(float, e)) for e in [lng_lat.split(" ") for lng_lat in ele.split(",")]]
                polygon.append(polygon[0])
                polygon = [polygon]
                multi_polygon.append(polygon)
            doc = {
                "country": "中国",
                "province": name[0],
                "city": name[1],
                "geo": {
                    "type": "Point",
                    "coordinates": [geo[0], geo[1]]
                },
                "multi_polygon": {
                    "type": "MultiPolygon",
                    "coordinates": multi_polygon
                }
            }
            collection.insert_one(doc)
            print("Saved: " + ','.join(name))
        else:
            print("Skip this record")

Mongo 创建一下索引 db.city_polygon.createIndex({"multi_polygon": "2dsphere"})

然后可以查询一下试试

db.city_polygon.find({
    multi_polygon: {
        $geoIntersects: {
            $geometry: {
                type: "Point",
                coordinates: [116.404598,39.913416]
            }
        }
    }
})

返回北京这条数据。

除了塞进 Mongo 也可以自己拿数据去算,比如射线法之类的,有兴趣可以研究一下

标签:multi,省市,mongo,经纬度,db,name,名称,geo,polygon
From: https://www.cnblogs.com/seliote/p/17091425.html

相关文章