How to use Python with pandas exporting Data to GeoJSON for Google Map

Viewed 9169

I am doing a project about web crawler.
I will got some point location include (Name, longitude, latitude)
Then point all of them in Google Map(use Google Map API)


First
I got some data from the website API. -- (300points locaiton)
Then use Python pandas DataFrame to export Json File

df = pd.DataFrame(total, columns=['name','lat', 'lng'])
df['lat'] = pd.to_numeric(df['lat'])
df['lng'] = pd.to_numeric(df['lng'])

jsonFile = df.to_json(orient='records')
with open('map.json','w') as f:
    f.write(jsonFile)

json structure look like this

{
"name":"臺中女中",
"lat":24.13604,
"lng":120.6778
}

So here is the problem:
How can I import those of point to Google Map use Google Map API
I've tried to read the Google Map API Document, it just tell me to use

map.data.loadGeoJson('map.json');

Finally i got wrong. and the Error Message

uncaught exception: InvalidValueError: not a Feature or FeatureCollection

Is Google Map API only support GeoJson?
How can I change my json file to the GeoJson?
or how can I modify my json file that can use in Google Map API.
Thank you very much.

1 Answers

How can I change my json file to the GeoJson?

You could use geojson

Here's an example:

Import:

import json
import pandas as pd
from geojson import Feature, FeatureCollection, Point

DataFrame:

df = pd.DataFrame([{'name': '臺中女中', 'lat': 24.13604, 'lng': 120.6778}])

Converting to geojson:

# columns used for constructing geojson object
features = df.apply(
    lambda row: Feature(geometry=Point((float(row['lng']), float(row['lat'])))),
    axis=1).tolist()

# all the other columns used as properties
properties = df.drop(['lat', 'lng'], axis=1).to_dict('records')

# whole geojson object
feature_collection = FeatureCollection(features=features, properties=properties)

Then you could save your geojson file:

with open('/path/to/your/file.geojson', 'w', encoding='utf-8') as f:
    json.dump(feature_collection, f, ensure_ascii=False)
Related