{"id":281,"date":"2017-07-23T03:25:40","date_gmt":"2017-07-23T02:25:40","guid":{"rendered":"http:\/\/192.168.1.18\/?page_id=281"},"modified":"2018-11-15T23:47:29","modified_gmt":"2018-11-15T23:47:29","slug":"python-code-snippets-gecode","status":"publish","type":"page","link":"http:\/\/www.bulis.co.uk\/?page_id=281","title":{"rendered":"Python: Code Snippets &#8211; Geocode"},"content":{"rendered":"<blockquote><p><span style=\"color: #ff0000;\">UPDATE:- Google are no longer offering API keys without billing information<\/span><\/p><\/blockquote>\n<p><span class=\"_Tgc\"><b>Geocoding<\/b> is the process of converting locations (a street address, postcode etc.) into coordinates; latitude and longitude. <\/span><\/p>\n<p>The first script takes these coordinates and returns an image of the location.<\/p>\n<p>To run this script copy the code below and save to a file called geocode_image.py<\/p>\n<p>geocode_image.py:<\/p>\n<pre class=\"brush: python; title: ; notranslate\" title=\"\">\r\n#!\/usr\/bin\/env python\r\n\r\n# Geocode map image\r\n# Return an image for a given location\r\n# (latitude and longitude)\r\n\r\n# Date: 07 March 2016\r\n# Written By: Phantom Raspberry Blower\r\n\r\nimport Image\r\nimport urllib\r\nimport StringIO\r\nimport os\r\nfrom math import log, exp, tan, atan, pi, ceil\r\n\r\n# Define constants\r\nEARTH_RADIUS = 6378137  # in metres\r\nEQUATOR_CIRCUMFERENCE = 2 * pi * EARTH_RADIUS\r\nINITIAL_RESOLUTION = EQUATOR_CIRCUMFERENCE \/ 256.0\r\nORIGIN_SHIFT = EQUATOR_CIRCUMFERENCE \/ 2.0\r\n\r\n\r\nclass GeocodeImage():\r\n\r\n    # Initialize\r\n    def __init__(self):\r\n        pass  # Do nothing\r\n\r\n    def latlontopixels(self, lat, lon, zoom):\r\n        mx = (lon * ORIGIN_SHIFT) \/ 180.0\r\n        my = log(tan((90 + lat) * pi \/ 360.0))\/(pi \/ 180.0)\r\n        my = (my * ORIGIN_SHIFT) \/ 180.0\r\n        res = INITIAL_RESOLUTION \/ (2 ** zoom)\r\n        px = (mx + ORIGIN_SHIFT) \/ res\r\n        py = (my + ORIGIN_SHIFT) \/ res\r\n        return px, py\r\n\r\n    def pixelstolatlon(self, px, py, zoom):\r\n        res = INITIAL_RESOLUTION \/ (2**zoom)\r\n        mx = px * res - ORIGIN_SHIFT\r\n        my = py * res - ORIGIN_SHIFT\r\n        lat = (my \/ ORIGIN_SHIFT) * 180.0\r\n        lat = 180 \/ pi * (2*atan(exp(lat*pi\/180.0)) - pi\/2.0)\r\n        lon = (mx \/ ORIGIN_SHIFT) * 180.0\r\n        return lat, lon\r\n\r\n    def geocode_image(self, lat, lon, file_path):\r\n        plat, plon = self.latlontopixels(lat, lon, 17)\r\n        nlat, nlon = self.pixelstolatlon(plat-320, plon+180, 17)\r\n        upperleft = '%f,%f' % (nlat, nlon)\r\n        plat, plon = self.latlontopixels(nlat, nlon, 17)\r\n        nlat, nlon = self.pixelstolatlon(plat+640, plon-360, 17)\r\n        lowerright = '%f,%f' % (nlat, nlon)\r\n        zoom = 18 # be careful not to get too many images!\r\n        map_type = 'hybrid'\r\n        ullat, ullon = map(float, upperleft.split(','))\r\n        lrlat, lrlon = map(float, lowerright.split(','))\r\n        # Set some important parameters\r\n        scale = 1\r\n        maxsize = 640\r\n        # convert all these coordinates to pixels\r\n        ulx, uly = self.latlontopixels(ullat, ullon, zoom)\r\n        lrx, lry = self.latlontopixels(lrlat, lrlon, zoom)\r\n        # calculate total pixel dimensions of final image\r\n        dx, dy = abs(lrx - ulx), abs(uly - lry)\r\n        # calculate rows and columns\r\n        cols, rows = int(ceil(dx\/maxsize)), int(ceil(dy\/maxsize))\r\n        # calculate pixel dimensions of each small image\r\n        bottom = 120\r\n        length = int(ceil(dx\/cols))\r\n        height = int(ceil(dy\/rows))\r\n        heightplus = height + bottom\r\n        final = Image.new(&quot;RGB&quot;, (int(dx), int(dy)))\r\n        for x in range(cols):\r\n            for y in range(rows):\r\n                dxn = length * (0.5 + x)\r\n                dyn = height * (0.5 + y)\r\n                latn, lonn = self.pixelstolatlon(ulx + dxn,\r\n                                                 uly - dyn - bottom\/2,\r\n                                                 zoom)\r\n                position = ','.join((str(latn), str(lonn)))\r\n                print x, y, position\r\n                urlparams = urllib.urlencode({'center': position,\r\n                                              'zoom': str(zoom),\r\n                                              'size': '%dx%d' % (length,\r\n                                                                 heightplus),\r\n                                              'maptype': map_type,\r\n                                              'sensor': 'false',\r\n                                              'scale': scale})\r\n                url = 'http:\/\/maps.google.com\/maps\/api\/staticmap?' + urlparams\r\n                f = urllib.urlopen(url)\r\n                im = Image.open(StringIO.StringIO(f.read()))\r\n                final.paste(im, (int(x*length), int(y*height)))\r\n                final.save(file_path)\r\n        final.show()\r\n        return final\r\n\r\n# Check if running stand-alone or imported\r\nif __name__ == '__main__':\r\n    import os\r\n    # Request both latitude and longitude\r\n    latitude = input('Enter Latitude: ')\r\n    longitude = input('Enter Longitude: ')\r\n    gi = GeocodeImage()\r\n    print &quot;Fetching image ...&quot;\r\n    gi.geocode_image(latitude,\r\n    longitude,\r\n    os.getcwd() + '\/geocode_image.jpg')\r\n    print &quot;Image saved!&quot;\r\n\r\n<\/pre>\n<p>The next script accepts an address, location or postcode and returns the latitude and longitude.<\/p>\n<p>Copy the code below and save to a file called geocode.py<\/p>\n<p>geocode.py:<\/p>\n<pre class=\"brush: python; title: ; notranslate\" title=\"\">\r\n#!\/usr\/bin\/env python\r\n\r\n# Geocode\r\n# Return the address and location for a given postcode\r\n\r\n# Date: 07 March 2016\r\n# Written By: Phantom Raspberry Blower\r\n\r\nimport requests # Used to request web pages\r\nimport Image\r\nimport urllib\r\nimport StringIO\r\nfrom geocode_image import GeocodeImage\r\n\r\n\r\nclass Geocode():\r\n\r\n    # Initialize\r\n    def __init__(self):\r\n        self.addr = ''\r\n\r\n    def geocode_postcode(self, postcode):\r\n        self.geocode(postcode)\r\n\r\n    def _clear(self):\r\n        self.post_code = ''\r\n        self.addr = ''\r\n        self.addr_label = ''\r\n        self.formatted_addr = ''\r\n        self.lat = 0.0\r\n        self.lon = 0.0\r\n\r\n    def geocode(self, postcode):\r\n        self._clear()\r\n        self.post_code = postcode.upper()\r\n        url = 'https:\/\/maps.googleapis.com\/maps\/api\/geocode\/json'\r\n        params = {'sensor': 'false', 'address': postcode}\r\n        r = requests.get(url, params=params)\r\n        results = r.json()&#x5B;'results']\r\n        location = results&#x5B;0]&#x5B;'geometry']&#x5B;'location']\r\n        self.lat = location&#x5B;'lat']\r\n        self.lon = location&#x5B;'lng']\r\n        address_components = results&#x5B;0]&#x5B;'address_components']\r\n        for item in range(1, len(address_components)):\r\n            if item &amp;amp;gt; 1:\r\n                self.addr = &quot;%s\\n&quot; % self.addr\r\n            self.addr = &quot;%s%s&quot; % (self.addr, address_components&#x5B;item]&#x5B;'long_name'])\r\n        self.formatted_addr = results&#x5B;0]&#x5B;'formatted_address']\r\n\r\n    def image(self): \r\n        gi = GeocodeImage()\r\n        gi.geocode_image(self.lat, self.lon, os.getcwd() + '\/geocode_image.jpg')\r\n        return &quot;Image Saved&quot;\r\n\r\n    def postcode(self):\r\n        return self.post_code\r\n\r\n    def location(self):\r\n        return &#x5B;self.latitude(), self.longitude()]\r\n\r\n    def latitude(self):\r\n        return self.lat\r\n\r\n    def longitude(self):\r\n        return self.lon\r\n\r\n    def address(self):\r\n        return self.addr\r\n\r\n    def address_label(self):\r\n        return str(self.formatted_address()).replace(&quot;, &quot;, &quot;,\\n&quot;)\r\n\r\n    def formatted_address(self):\r\n        return str(self.formatted_addr)\r\n\r\n# Check if running stand-alone or imported \r\nif __name__ == '__main__':\r\n    postcode = raw_input('Enter Address, Location or Postcode: ').upper()\r\n    gc = Geocode()\r\n    gc.geocode_postcode(postcode)\r\n    print &quot;\\nAddress:&quot;\r\n    print &quot;         &quot;, gc.address_label().replace(&quot;\\n&quot;, &quot;\\n          &quot;)\r\n    print &quot;\\nLocation:&quot;\r\n    print &quot;          Latitude: &quot;, gc.latitude()\r\n    print &quot;          Longitude: &quot;, gc.longitude()\r\n    print &quot;\\nSingle-line Address:&quot;\r\n    print &quot;         &quot;, gc.formatted_address(), &quot;\\n&quot;\r\n    gc.image()\r\n\r\n<\/pre>\n<p>Ouput:<\/p>\n<pre class=\"brush: bash; title: ; notranslate\" title=\"\">\r\npython geocode.py\r\nEnter Address, Location or Postcode: SW1A 1AA\r\n\r\nAddress:\r\n          London SW1A 1AA,\r\n          UK\r\n\r\nLocation:\r\n          latitude:   51.501009\r\n          longitude:  -0.1415876\r\n\r\nSingle-line Address:\r\n          London SW1A 1AA, UK\r\n\r\n0 0 51.5014095689,-0.143875696751\r\n0 1 51.5002073959,-0.143875696751\r\n1 0 51.5014095689,-0.141585090252\r\n1 1 51.5002073959,-0.141585090252\r\n2 0 51.5014095689,-0.139294483753\r\n2 1 51.5002073959,-0.139294483753\r\n\r\n<\/pre>\n<p>Image:<\/p>\n<div id=\"attachment_289\" style=\"width: 650px\" class=\"wp-caption aligncenter\"><a href=\"http:\/\/www.bulis.co.uk\/wp-content\/uploads\/2017\/07\/geocode_image.jpg\"><img aria-describedby=\"caption-attachment-289\" decoding=\"async\" loading=\"lazy\" class=\"wp-image-289 size-full\" title=\"Geocode Image\" src=\"http:\/\/www.bulis.co.uk\/wp-content\/uploads\/2017\/07\/geocode_image.jpg\" alt=\"Geocode Image\" width=\"640\" height=\"360\" \/><\/a><p id=\"caption-attachment-289\" class=\"wp-caption-text\">Geocode Image<\/p><\/div>\n","protected":false},"excerpt":{"rendered":"<p>UPDATE:- Google are no longer offering API keys without billing information Geocoding is the process of converting locations (a street address, postcode etc.) into coordinates; latitude and longitude. The first script takes these coordinates and returns an image of the location. To run this script copy the code below and save to a file called [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"parent":239,"menu_order":0,"comment_status":"closed","ping_status":"closed","template":"","meta":[],"acf":[],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v20.12 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>Python: Code Snippets - Geocode - Phantom Raspberry Blower<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"http:\/\/www.bulis.co.uk\/?page_id=281\" \/>\n<meta property=\"og:locale\" content=\"en_GB\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Python: Code Snippets - Geocode - Phantom Raspberry Blower\" \/>\n<meta property=\"og:description\" content=\"UPDATE:- Google are no longer offering API keys without billing information Geocoding is the process of converting locations (a street address, postcode etc.) into coordinates; latitude and longitude. The first script takes these coordinates and returns an image of the location. To run this script copy the code below and save to a file called [&hellip;]\" \/>\n<meta property=\"og:url\" content=\"http:\/\/www.bulis.co.uk\/?page_id=281\" \/>\n<meta property=\"og:site_name\" content=\"Phantom Raspberry Blower\" \/>\n<meta property=\"article:modified_time\" content=\"2018-11-15T23:47:29+00:00\" \/>\n<meta property=\"og:image\" content=\"http:\/\/www.bulis.co.uk\/wp-content\/uploads\/2017\/07\/geocode_image.jpg\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Estimated reading time\" \/>\n\t<meta name=\"twitter:data1\" content=\"5 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"WebPage\",\"@id\":\"http:\/\/www.bulis.co.uk\/?page_id=281\",\"url\":\"http:\/\/www.bulis.co.uk\/?page_id=281\",\"name\":\"Python: Code Snippets - Geocode - Phantom Raspberry Blower\",\"isPartOf\":{\"@id\":\"http:\/\/www.bulis.co.uk\/#website\"},\"datePublished\":\"2017-07-23T02:25:40+00:00\",\"dateModified\":\"2018-11-15T23:47:29+00:00\",\"breadcrumb\":{\"@id\":\"http:\/\/www.bulis.co.uk\/?page_id=281#breadcrumb\"},\"inLanguage\":\"en-GB\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"http:\/\/www.bulis.co.uk\/?page_id=281\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"http:\/\/www.bulis.co.uk\/?page_id=281#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"http:\/\/www.bulis.co.uk\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Tutorials\",\"item\":\"http:\/\/www.bulis.co.uk\/?page_id=57\"},{\"@type\":\"ListItem\",\"position\":3,\"name\":\"Python Tutorials\",\"item\":\"http:\/\/www.bulis.co.uk\/?page_id=73\"},{\"@type\":\"ListItem\",\"position\":4,\"name\":\"Python: Code Snippets\",\"item\":\"http:\/\/www.bulis.co.uk\/?page_id=239\"},{\"@type\":\"ListItem\",\"position\":5,\"name\":\"Python: Code Snippets &#8211; Geocode\"}]},{\"@type\":\"WebSite\",\"@id\":\"http:\/\/www.bulis.co.uk\/#website\",\"url\":\"http:\/\/www.bulis.co.uk\/\",\"name\":\"Phantom Raspberry Blower\",\"description\":\"Blowing Raspberrys since 1989\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"http:\/\/www.bulis.co.uk\/?s={search_term_string}\"},\"query-input\":\"required name=search_term_string\"}],\"inLanguage\":\"en-GB\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Python: Code Snippets - Geocode - Phantom Raspberry Blower","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"http:\/\/www.bulis.co.uk\/?page_id=281","og_locale":"en_GB","og_type":"article","og_title":"Python: Code Snippets - Geocode - Phantom Raspberry Blower","og_description":"UPDATE:- Google are no longer offering API keys without billing information Geocoding is the process of converting locations (a street address, postcode etc.) into coordinates; latitude and longitude. The first script takes these coordinates and returns an image of the location. To run this script copy the code below and save to a file called [&hellip;]","og_url":"http:\/\/www.bulis.co.uk\/?page_id=281","og_site_name":"Phantom Raspberry Blower","article_modified_time":"2018-11-15T23:47:29+00:00","og_image":[{"url":"http:\/\/www.bulis.co.uk\/wp-content\/uploads\/2017\/07\/geocode_image.jpg"}],"twitter_card":"summary_large_image","twitter_misc":{"Estimated reading time":"5 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"WebPage","@id":"http:\/\/www.bulis.co.uk\/?page_id=281","url":"http:\/\/www.bulis.co.uk\/?page_id=281","name":"Python: Code Snippets - Geocode - Phantom Raspberry Blower","isPartOf":{"@id":"http:\/\/www.bulis.co.uk\/#website"},"datePublished":"2017-07-23T02:25:40+00:00","dateModified":"2018-11-15T23:47:29+00:00","breadcrumb":{"@id":"http:\/\/www.bulis.co.uk\/?page_id=281#breadcrumb"},"inLanguage":"en-GB","potentialAction":[{"@type":"ReadAction","target":["http:\/\/www.bulis.co.uk\/?page_id=281"]}]},{"@type":"BreadcrumbList","@id":"http:\/\/www.bulis.co.uk\/?page_id=281#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"http:\/\/www.bulis.co.uk\/"},{"@type":"ListItem","position":2,"name":"Tutorials","item":"http:\/\/www.bulis.co.uk\/?page_id=57"},{"@type":"ListItem","position":3,"name":"Python Tutorials","item":"http:\/\/www.bulis.co.uk\/?page_id=73"},{"@type":"ListItem","position":4,"name":"Python: Code Snippets","item":"http:\/\/www.bulis.co.uk\/?page_id=239"},{"@type":"ListItem","position":5,"name":"Python: Code Snippets &#8211; Geocode"}]},{"@type":"WebSite","@id":"http:\/\/www.bulis.co.uk\/#website","url":"http:\/\/www.bulis.co.uk\/","name":"Phantom Raspberry Blower","description":"Blowing Raspberrys since 1989","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"http:\/\/www.bulis.co.uk\/?s={search_term_string}"},"query-input":"required name=search_term_string"}],"inLanguage":"en-GB"}]}},"_links":{"self":[{"href":"http:\/\/www.bulis.co.uk\/index.php?rest_route=\/wp\/v2\/pages\/281"}],"collection":[{"href":"http:\/\/www.bulis.co.uk\/index.php?rest_route=\/wp\/v2\/pages"}],"about":[{"href":"http:\/\/www.bulis.co.uk\/index.php?rest_route=\/wp\/v2\/types\/page"}],"author":[{"embeddable":true,"href":"http:\/\/www.bulis.co.uk\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"http:\/\/www.bulis.co.uk\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=281"}],"version-history":[{"count":2,"href":"http:\/\/www.bulis.co.uk\/index.php?rest_route=\/wp\/v2\/pages\/281\/revisions"}],"predecessor-version":[{"id":1634,"href":"http:\/\/www.bulis.co.uk\/index.php?rest_route=\/wp\/v2\/pages\/281\/revisions\/1634"}],"up":[{"embeddable":true,"href":"http:\/\/www.bulis.co.uk\/index.php?rest_route=\/wp\/v2\/pages\/239"}],"wp:attachment":[{"href":"http:\/\/www.bulis.co.uk\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=281"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}