I made a program to get the name of the city, town, and village of this point only from the latitude and longitude information of any point. There are two points: reading the shapefile and judging the inside and outside of the point.
I used two types of modules, pyshp and Sympy (installed with pip). -Pyshp (used to read shp files) ・ Sympy (used for internal / external judgment) ・ Shapefile of the boundary of municipalities (Reference: https://www.esrij.com/products/japan-shp/)
The source code is as follows.
import shapefile
from sympy.geometry import Point, Polygon
#
LONG=140.0
LAT=36.5
RPOINT=Point(LONG,LAT)  #➀ Judgment target point setting
#
src=shapefile.Reader('.\\shp\\japan_ver821.shp',encoding='SHIFT-JIS')  #File reading
SRS=src.shapeRecords()  #➁ shp data reading
for srs in SRS:
    shp=srs.shape   #➁ Acquisition of feature information
    rec=srs.record  #➁ Attribute information acquisition
    box=shp.bbox    #➁ Get the rectangle that surrounds each object
    #
    #➂ If the target point is within a rectangle, perform a more detailed internal / external judgment
    if box[0]<LONG<box[2] and box[1]<LAT<box[3]:  
        pnt=shp.points  #➃ Get coordinate information of each object
        points=[]       #➃ Extract nodes of each object
        for pp in pnt:   
            points.append((pp[0],pp[1]))
        poly=Polygon(*points)   #➃ Create sympy polygon data
        #
        if poly.encloses_point(RPOINT):  #➃ Conduct internal / external judgment
            print(rec)                   #➄ Output city / town / village information
            break
The following processes are performed in order. ① Judgment target point setting ② Read shp data ③ Check if there is a judgment target point within the rectangular range of each object ④ ③ If there is a target point within the range, carry out a more detailed internal / external judgment ⑤ Output attribute information when internal / external judgment is successful
Record #469: ['Tochigi Prefecture', '', '', '', 'Utsunomiya City']
I was able to get the name of the city.
This method doesn't seem to work if the shp data contains donut-shaped polygons consisting of two or more closed curves. In such a case, we would appreciate it if you could refer to the following. https://qiita.com/Pooh-A/items/6b4fcb15a790f6ee6e79
Recommended Posts