Added Geocoode API program

This commit is contained in:
Mysterious-Owl 2022-10-09 23:58:15 +05:30
parent a8aa52077c
commit dcab9228de
7 changed files with 176 additions and 0 deletions

View File

@ -0,0 +1,16 @@
# Google Maps API
This code will take the name of places from where.txt and then use *forward Geocode API* to get the coordinates of that location, then the coordinates are stored in javascript file and the webpage is opened automatically, to show the pin locations on map.<br>
### Prerequisites
To install configparser ```pip install configparser``` or check [here](https://pypi.org/project/configparser/)
If you have [Google Geocode API](https://developers.google.com/maps/documentation/geocoding/overview), so use that, otherwise you can use
[Open Cage API](https://opencagedata.com/api) (its free, 2500 requests/day).
### How to run the script
Enter the API key and service URL in config file (without qoutes) and the places to be marked in where.txt file, then run the script.

View File

@ -0,0 +1,61 @@
import urllib.request
import urllib.parse
import urllib.error
import json
import os
import webbrowser
import ssl
import configparser
config = configparser.ConfigParser()
config.read('config.ini')
api_key = config['keys']['api_key']
service_url = config['keys']['service_url']
# Ignore SSL certificate errors
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
with open("where.txt") as fh, open("where.js", "w", encoding="utf-8") as where:
adrs = []
parms = {}
for line in fh:
address = line.strip()
parms["address"] = address
parms['key'] = api_key
url = service_url + urllib.parse.urlencode(parms)
if url.lower().startswith('http'):
req = urllib.request.Request(url)
else:
raise ValueError from None
with urllib.request.urlopen(req, context=ctx) as resp:
data = resp.read().decode()
try:
js = json.loads(data)
except Exception as e:
print(f"{e}: {data}")
continue
try:
adrs.append([js['results'][0]['geometry']['lat'],
js['results'][0]['geometry']['lng'],
js['results'][0]['formatted']])
print('Retrieved ', url)
except Exception as e:
print(f"Not Found: {e}: {line.strip()}")
print("\nOpening Webpage")
where.write("myData = [\n")
for item in adrs:
where.write(f"[{str(item[0])}, {str(item[1])}, '{str(item[2])}' ], \n")
where.write("];\n")
webbrowser.open('file://' + os.path.realpath("index.html"))

View File

@ -0,0 +1,3 @@
[keys]
service_url=https://api.opencagedata.com/geocode/v1/json?q=
api_key=

View File

@ -0,0 +1,48 @@
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>GOOGLE MAPS API</title>
<link href="https://google-developers.appspot.com/maps/documentation/javascript/examples/default.css" rel="stylesheet">
<script src="https://maps.googleapis.com/maps/api/js"></script>
<script src="where.js"></script>
<script>
function initialize() {
var myLatlng = new google.maps.LatLng(37.39361,-122.099263)
var mapOptions = {
zoom: 3,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
i = 0;
var markers = [];
for ( pos in myData ) {
i = i + 1;
var row = myData[pos];
window.console && console.log(row);
var newLatlng = new google.maps.LatLng(row[0], row[1]);
var marker = new google.maps.Marker({
position: newLatlng,
map: map,
title: row[2]
});
markers.push(marker);
var options = {
imagePath: 'http://rawgit.com/googlemaps/js-marker-clusterer/gh-pages/images/m'
}
}
var markerCluster = new MarkerClusterer(map, markers, options);
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas" style="height: 500px"></div>
<p><b>About this Map</b></p>
<p>
This is a cool script by
<a href="https://github.com/Mysterious-Owl">Mysterious-Owl</a> with the use of API.<br>
To see the details of a marker, hover over the marker.
</p>
</body>
</html>

View File

@ -0,0 +1,2 @@
configparser
ssl

View File

@ -0,0 +1,24 @@
myData = [
[41.89193, 12.51133, 'Rome, Italy' ],
[12.937243, 77.6925796, 'The Address, Outer Ring Road, Kaadubeesanahalli, Bengaluru - 530103, Karnataka, India' ],
[51.575646, -0.0986474, 'Address, Endymion Road, London, N4 1EQ, United Kingdom' ],
[-33.86785, 151.20732, 'Sydney, Australia' ],
[35.6718484, 139.7419907, 'Address Building, Sotobori-dori, Akasaka 2-chome, Minato, 100-8968, Japan' ],
[55.75222, 37.61556, 'Moscow, Russia' ],
[34.05223, -118.24368, 'Los Angeles, California, United States of America' ],
[-23.582841, -46.6847335, 'Hotel Intercity Adress Faria Lima, Rua Amauri 513, Vila Olímpia, São Paulo - SP, 01453-020, Brazil' ],
[-33.92584, 18.42322, 'Cape Town, City of Cape Town, South Africa' ],
[22.28552, 114.15769, 'Hong Kong' ],
[30.0439192, 30.9812426, 'District 12, Sheikh Zayed, Giza, Egypt' ],
[43.6557254, -79.456573, 'The Address at High Park, 1638 Bloor Street West, Toronto, ON M6P 0A6, Canada' ],
[-20.0, 47.0, 'Madagascar' ],
[1.114186, 103.9852544, 'Manisee Syariah Homestay (actual address), Tiban Mc Dermoth, Batam City 29427, Riau Islands, Indonesia' ],
[64.00028, -150.00028, 'Alaska, United States of America' ],
[18.0, -2.0, 'Mali' ],
[60.0, 100.0, 'Russia' ],
[62.0, 10.0, 'Norway' ],
[-23.2029627, -65.3474844, 'La Nueva Puerta Verde good (good address), Avenida General Belgrano, Humahuaca, Municipio de Humahuaca, Argentina' ],
[20.75028, -156.50028, 'Hawaii, United States of America' ],
[46.0, 105.0, 'Mongolia' ],
[-37.9032307, 144.7585649, 'The Address, Point Cook VIC 3030, Australia' ],
];

View File

@ -0,0 +1,22 @@
rome
delhi
london
sydney
japan
moscow
los angeles
brazil
cape town
hong kong
egypt
canada
madagascar
indonesia
alaska
mali
russia
norway
argentina
hawaii
mongolia
australia