Viz Geodata
https://www.youtube.com/embed/KfhslNzopxo
Code Sample
-
geoload.py
import urllib.request, urllib.parse, urllib.error import http import sqlite3 import json import time import ssl import sys serviceurl = 'https://py4e-data.dr-chuck.net/opengeo?' # Additional detail for urllib # http.client.HTTPConnection.debuglevel = 1 # Make database conn = sqlite3.connect('opengeo.sqlite') cur = conn.cursor() # create table cur.execute(''' CREATE TABLE IF NOT EXISTS Locations (address TEXT, geodata TEXT)''') # Ignore SSL certificate errors ctx = ssl.create_default_context() ctx.check_hostname = False ctx.verify_mode = ssl.CERT_NONE fh = open("where.data") count = 0 nofound = 0 for line in fh: if count > 100 : print('Retrieved 100 locations, restart to retrieve more') break address = line.strip() print('') cur.execute("SELECT geodata FROM Locations WHERE address= ?", (memoryview(address.encode()), )) try: data = cur.fetchone()[0] print("Found in database", address) continue except: pass # make dictionary parms = dict() parms['q'] = address url = serviceurl + urllib.parse.urlencode(parms) print('Retrieving', url) uh = urllib.request.urlopen(url, context=ctx) data = uh.read().decode() print('Retrieved', len(data), 'characters', data[:20].replace('\n', ' ')) count = count + 1 try: js = json.loads(data) except: print(data) # We print in case unicode causes an error continue if not js or 'features' not in js: print('= Download error ') print(data) break if len(js['features']) == 0: print('= Object not found ') nofound = nofound + 1 # Insert new data we just get cur.execute('''INSERT INTO Locations (address, geodata) VALUES ( ?, ? )''', (memoryview(address.encode()), memoryview(data.encode()) ) ) conn.commit() if count % 10 == 0 : print('Pausing for a bit...') time.sleep(5) if nofound > 0: print('Number of features for which the location could not be found:', nofound) print("Run geodump.py to read the data from the database so you can vizualize it on a map.") -
geodump.py
import sqlite3 import json import codecs conn = sqlite3.connect('opengeo.sqlite') cur = conn.cursor() cur.execute('SELECT * FROM Locations') fhand = codecs.open('where.js', 'w', "utf-8") fhand.write("myData = [\n") count = 0 for row in cur : data = str(row[1].decode()) try: js = json.loads(str(data)) except: continue if len(js['features']) == 0: continue try: lat = js['features'][0]['geometry']['coordinates'][1] lng = js['features'][0]['geometry']['coordinates'][0] where = js['features'][0]['properties']['display_name'] where = where.replace("'", "") except: print('Unexpected format') print(js) try : print(where, lat, lng) count = count + 1 if count > 1 : fhand.write(",\n") output = "["+str(lat)+","+str(lng)+", '"+where+"']" fhand.write(output) except: continue fhand.write("\n];\n") cur.close() fhand.close() print(count, "records written to where.js") print("Open where.html to view the data in a browser") -
where.js
myData = [ [50.065703299999996,19.918958667058632, 'AGH University of Science and Technology'], [52.2394966,21.015693129786936, 'Academy of Fine Arts in Warsaw'], [30.04281175,31.23658590813949, 'American University in Cairo'], [33.42152185,-111.93316158417922, 'Arizona State University'], [37.9425172,23.8706149, 'Athens Information Technology'], [17.547231,78.5725623, 'bits pilani'], [6.88997525,3.7224790878605756, 'Babcock University'], [25.2662887,82.9927969, 'Banaras Hindu University'], [12.944172049999999,77.5091485894286, 'Bangalore University'], [31.55043405,-97.1102905567766, 'Baylor University'], [39.959732,116.35973698189176, 'Beijing Normal University (BNU)'], [53.83806745,27.476155257195504, 'Belarusian State University'], [44.8179516,20.450674096755193, 'University of Arts in Belgrade'], [42.5009819,-89.0157777411969, 'Beloit College'], [35.95422,-90.45997, 'Beloit College'], [31.2631254,34.802238544584185, 'Ben Gurion University of the Negev'], [42.35031725,-71.10122725124097, 'Boston University'], [35.3074623,-120.66464833678835, 'California Polytechnic State University'], [34.18191745,-117.32174391836504, 'California State University, San Bernardino'], [51.5213399,-0.1748934415893599, 'City of Westminster College'], [40.8077627,-73.96164061324416, 'Columbia University'] ]; -
where.html
<!doctype html> <html lang="pl"> <head> <meta charset="utf-8"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.4.3/css/ol.css" type="text/css"> <style> body {font-family: Verdana, Geneva, sans-serif;} .map { height: 400px; width: 100%; } .ol-popup { position: absolute; background-color: white; -webkit-filter: drop-shadow(0 1px 4px rgba(0,0,0,0.2)); filter: drop-shadow(0 1px 4px rgba(0,0,0,0.2)); padding: 15px; border-radius: 10px; border: 1px solid #cccccc; bottom: 12px; left: -50px; min-width: 150px; } .ol-popup:after, .ol-popup:before { top: 100%; border: solid transparent; content: " "; height: 0; width: 0; position: absolute; pointer-events: none; } .ol-popup:after { border-top-color: white; border-width: 10px; left: 48px; margin-left: -10px; } .ol-popup:before { border-top-color: #cccccc; border-width: 11px; left: 48px; margin-left: -11px; } .ol-popup-closer { text-decoration: none; position: absolute; top: 2px; right: 8px; } .ol-popup-closer:after { content: "x"; } </style> <script src="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.4.3/build/ol.js"></script> <script src="where.js"></script> <title>Mapa informacji</title> </head> <body> <div id="map" class="map"></div> <div id="popup" class="ol-popup"> <a href="#" id="popup-closer" class="ol-popup-closer"></a> <div id="popup-content"></div> </div> <p><b>About the map</b></p> <p>If you would like to make this map yourself, please visit <a href="https://www.py4e.com/">www.py4e.com</a></p> <p>The original Polish version of the code for this map came from <a href="https://py4e.pl">py4e.pl</a>. <p>Map generated <script>document.write(new Date());</script></p> </p> <script type="text/javascript"> /** * Elements that make up the popup. */ var container = document.getElementById('popup'); var content = document.getElementById('popup-content'); var closer = document.getElementById('popup-closer'); /** * Add a click handler to hide the popup. * @return {boolean} Don't follow the href. */ closer.onclick = function() { overlay.setPosition(undefined); closer.blur(); return false; }; /** * Create an overlay to anchor the popup to the map. */ var overlay = new ol.Overlay({ element: container, autoPan: true, autoPanAnimation: { duration: 250 } }); var map = new ol.Map({ target: 'map', overlays: [overlay], layers: [ new ol.layer.Tile({ source: new ol.source.OSM() }) ], view: new ol.View({ center: ol.proj.fromLonLat([16.119735, 48.098628]), zoom: 4 }) }); var features = []; for ( pos in myData ) { var row = myData[pos]; var longitude = row[1]; var latitude = row[0]; var iconFeature = new ol.Feature({ geometry: new ol.geom.Point(ol.proj.transform([longitude, latitude], 'EPSG:4326', 'EPSG:3857')), name: row[2] }); var iconStyle = new ol.style.Style({ image: new ol.style.Icon(({ anchor: [0.5, 1], src: "https://cdn.mapmarker.io/api/v1/font-awesome/v5/pin?icon=fa-university&size=40&hoffset=0&voffset=0" })) }); iconFeature.setStyle(iconStyle); features.push(iconFeature); } var vectorSource = new ol.source.Vector({ features: features }); var vectorLayer = new ol.layer.Vector({ source: vectorSource }); map.addLayer(vectorLayer); /** * Add a click handler to the map to render the popup. */ map.on('singleclick', function(evt) { var name = map.forEachFeatureAtPixel(evt.pixel, function(feature) { return feature.get('name'); }) if (name) { container.style.display="block"; var coordinate = evt.coordinate; content.innerHTML = name; overlay.setPosition(coordinate); } else { container.style.display="none"; } }); map.on('pointermove', function(evt) { map.getTargetElement().style.cursor = map.hasFeatureAtPixel(evt.pixel) ? 'pointer' : ''; }); /* http://www.geocodezip.com/OL_5.3.0_simpleMultipleMarkerExample.html */ /* https://openlayers.org/ */ </script> </body> </html> -
open where.html in the browser

-
Open database in SQL browser (opengeo.sqlite)