Select Page

Creation

Postal addresses are typically long and every now and then tough to keep in mind. There are a selection of situations the place a shorter deal with could be fascinating. As an example, being able to ship a quick deal with consisting of best a few characters may be sure quicker supply of emergency ambulance services and products. Pieter Geelen and Harold Goddijn evolved the Mapcode system in 2001 to make it simple to create a short-form deal with for any bodily deal with on the planet.

On this educational, you’ll broaden a internet app that makes use of the Google Maps API to generate a quick virtual deal with for any deal with of your selection. You’ll do that through cloning the bottom code for this app from GitHub after which including code to it that can make it absolutely practical. This app can even be capable to retrieve the unique bodily deal with from a given mapcode.

Must haves

To be able to entire this educational, you’ll want the next:

Step 1 — Getting a Google API Key

On this educational, you’ll use JavaScript to create an interface to Google Maps. Google assigns API keys to allow builders to make use of the JavaScript API on Google Maps, which it is important to download and upload on your internet app’s code.

To get your personal API key, head to Google’s “Get API Key” page. Click on at the GET STARTED button in Step 1, and a pop-up will open as proven within the following symbol:

Choose Maps through clicking the test field and hit CONTINUE. For those who don’t seem to be already logged right into a Google account, you’ll be requested to take action. Then, the window will ask you to offer a reputation for the mission, which may also be anything else you need:

Following this, it’s going to ask you to go into your billing data. Observe that Google supplies API keys as a part of a unfastened trial, but it surely calls for you to arrange and allow billing so as retrieve them.

After getting into this knowledge, your API key will seem at the display. Replica and retailer it in a location the place you’ll simply retrieve it, as it is important to upload it on your mission code in a while.

After acquiring your API key, you’ll start construction the basis of your software through making a MySQL database.

Step 2 — Developing the Database

The internet software described on this educational accepts an deal with from the person and generates a mapcode for it together with the latitude and longitude of the required location. You’ll retailer this knowledge in a MySQL database in an effort to retrieve it in a while simply by getting into the respective virtual deal with.

Start through opening the MySQL shell and authenticating together with your password:

On the urged, create a database referred to as digitaladdress the usage of the next command:

  • CREATE DATABASE IF NOT EXISTS `digitaladdress`;

Subsequent, make a selection this new database in an effort to create a desk inside it:

After deciding on the digitaladdress database, create a desk referred to as places inside it to retailer the bodily deal with, its longitude, latitude, and the mapcode that your software will create from this knowledge. Run the next CREATE TABLE remark to create the places desk throughout the database:

  • CREATE TABLE `places` (
  • `digitaladdress` varchar(50) DEFAULT NULL,
  • `state` varchar(30) DEFAULT NULL,
  • `zip` varchar(30) DEFAULT NULL,
  • `side road` varchar(30) DEFAULT NULL,
  • `the city` varchar(30) DEFAULT NULL,
  • `space` varchar(30) DEFAULT NULL,
  • `latitude` varchar(30) DEFAULT NULL,
  • `longitude` varchar(30) DEFAULT NULL,
  • KEY `digitaladdress` (`digitaladdress`)
  • );

This desk has 8 columns: digitaladdress, state, zip, side road, the city, space, latitude, and longitude. The primary column, digitaladdress, is listed the usage of the KEY command. Indexes in MySQL serve as in a similar way to how they paintings in an encyclopedia or different reference paintings. Any time you or your software factor a question containing a WHERE remark, MySQL reads each and every access in every column, row-by-row, which is able to turn into a particularly resource-intensive procedure as your desk accumulates increasingly entries. Indexing a column like this takes the information from the column and retail outlets it alphabetically in a separate location, because of this that MySQL is not going to have to seem thru each and every row within the desk. It best has to search out the information you might be searching for within the index after which bounce to the corresponding row within the desk.

After including this desk, go out the MySQL urged:

Together with your database and desk arrange and your Google Maps API key in hand, you are ready to create the mission itself.

Step 3 — Developing the Undertaking

As discussed within the advent, we will be able to clone the bottom code for this mission from GitHub after which upload some further code to make the appliance practical. The cause of this, slightly than strolling you in the course of the procedure of constructing every document and including the entire code your self, is to hurry up the method of having the app operating. It’ll additionally permit us to concentrate on including and figuring out the code that permits the app to keep in touch with each the Google Maps and Mapcode APIs.

You’ll be able to to find the skeleton code for the total mission on this GitHub project page. Use the next git command to clone the mission on your server:

  • git clone https://github.com/do-community/digiaddress.git

This may increasingly create a brand new folder referred to as digiaddress in your house listing. Transfer this listing on your server’s internet root. For those who adopted the LAMP stack educational related in the must haves, this would be the /var/www/html listing:

  • sudo mv digiaddress/ /var/www/html/

This mission accommodates a number of PHP and JS recordsdata to which you can upload some code in a while on this educational. To view the listing construction, first set up the tree package deal the usage of apt:

Then run the tree command with the digiaddress listing given as an issue:

  • tree /var/www/html/digiaddress/

Output

digiaddress/ ├── README.md ├── db.php ├── fetchaddress.php ├── findaddress.php ├── generateDigitalAddress.php ├── geoimplement.php ├── index.php └── js ├── createDigitialAddressApp.js └── findAddressApp.js

You’ll be able to see from this output that the mission is composed of six PHP recordsdata and two JavaScript recordsdata. In combination, those recordsdata create the appliance’s two major functionalities: making a mapcode from a bodily deal with, and deciphering a mapcode to retrieve the unique bodily deal with. The next recordsdata allow the primary capability:

  • index.php
  • geoimplement.php
  • generateDigitialAddress.php
  • db.php
  • createDigitialAddressApp.js

The index.php document accommodates the code for the appliance’s person interface (UI), which is composed of a kind the place customers can input a bodily deal with. The index.php document calls the geoimplement.php document any time a person submits the shape. geoimplement.php makes a decision to the Google Maps API and passes the deal with alongside to it. The Google server then responds with a JSON containing the required deal with’s data, together with its latitude and longitude. This knowledge is then handed to the generateDigitalAddress.php document which calls the Mapcode API to acquire a mapcode for the given location, as laid out in its latitude and longitude. The ensuing mapcode, together with the latitude, longitude, and the bodily deal with, are then saved within the database that you simply created in Step 2. db.php acts as a helper for this operation. The createDigitalAddressApp.js document plays a lot of operations that regulate the UX components noticed within the app, together with surroundings a marker and boundary rectangle at the Google Maps interface.

The remainder 3 recordsdata allow the second one serve as of the appliance — this is, retrieving a bodily deal with from a given mapcode:

  • findaddress.php
  • fetchaddress.php
  • findAddressApp.js

The findaddress.php document defines the appliance UI, which is distinct from the only outlined in index.php. The appliance accepts a previously-generated mapcode as an enter and shows the corresponding bodily deal with saved within the database. Each time a person submits this manner, findaddress.php sends a decision to fetchaddress.php which then retrieves the respective mapcode from the database. The findAddressApp.js document accommodates the helper code for surroundings a marker and a boundary rectangle at the Google Maps interface.

Check the set up through visiting http://your_server_ip/digiaddress for your browser, ensuring to modify your_server_ip to mirror your server’s IP deal with.

Observe: If you do not know your server’s IP deal with, you’ll run the next curl command. This command will print the web page content material of icanhazip.com, a website online that displays the IP deal with of the device getting access to it:

  • curl http://icanhazip.com

As soon as there, you’ll see this heading on the most sensible of your browser window:

Generate Virtual Cope with

This confirms that you’ve got as it should be downloaded the mission recordsdata. With that, allow us to continue with the improvement of the app’s number one serve as: producing a mapcode.

Step 4 — Growing the Software’s UI

Whilst the boilerplate code for the appliance interface is incorporated within the recordsdata you downloaded within the earlier step, you continue to want to make a couple of adjustments and additions to a few of these recordsdata to make the appliance practical and attractive for customers. We will be able to get began with updating the code to broaden the appliance’s UI.

Open the index.php document the usage of your most popular editor. Right here, we will use nano:

  • nano /var/www/html/digiaddress/index.php

Search for the next line of code:

/var/www/html/digiaddress/index.php

. . .%MINIFYHTMLad3eacf13278a724d2870e5e81d0c9ac6%. . .

Change with the Google API key you received in Step 1. After including your API key, the road will have to glance very similar to this:

/var/www/html/digiaddress/index.php

. . .%MINIFYHTMLad3eacf13278a724d2870e5e81d0c9ac7%. . .

Subsequent, to find the next remark within the index.php document:

/var/www/html/digiaddress/index.php

. . .
            
. . .

We will upload a couple of dozen strains of code underneath this remark which is able to create a kind the place customers can input the deal with of a bodily location which the appliance will use to generate a mapcode. Underneath this remark, upload the next highlighted code which creates a identify referred to as Input Cope with on the most sensible of the shape:

/var/www/html/digiaddress/index.php

. . .
            

            
Input Cope with
. . .

Beneath this, upload the next HTML code. This creates a kind with 5 textual content fields (together with their suitable labels) the place customers will enter their data:

/var/www/html/digiaddress/index.php

                . . .
                
placeholder="" ng-model="address.state"/>
identification="zip" ng-model="address.zip" disabled="disabled"/>
identification="town" ng-model="address.town" disabled="disabled"/>
placeholder="" ng-model="address.street" disabled="disabled"/>
placeholder="" ng-model="address.house" disabled="disabled"/>
. . .

Beneath the shape code, upload the next strains. Those create two hidden controls which move alongside the latitude and longitude data derived from any deal with submitted in the course of the kind:

/var/www/html/digiaddress/index.php

                            . . .
                            
. . .

Finally, shut out this segment through including the next code. This creates a Generate button which is able to permit customers to post the shape:

/var/www/html/digiaddress/index.php

                            . . .
                            
                    
                



. . .

After including those components, this segment of the document will have to fit this:

/var/www/html/digiaddress/index.php

. . .
            

            
Input Cope with


. . .

Save the document through urgent CTRL+O then ENTER, after which talk over with the appliance for your browser once more:

http://your_server_ip/digiaddress

You’ll see the newly-added kind fields and Generate button, and the appliance will have to appear to be this:

At this level, in the event you input deal with data into the shape and take a look at clicking the Generate button, not anything will occur. We will be able to upload the mapcode era capability in a while, however let’s first focal point on making this web page extra visually enticing through including a map which customers can engage with.

Step 5 — Including Google Maps Controls

When maps are displayed on a website online in the course of the Google Maps JavaScript API, they comprise person interface options that permit guests to have interaction with the map they see. Those options are referred to as controls. We will be able to proceed enhancing the index.php document so as to add Google Maps controls to this app and, when completed, customers will be capable to view a map subsequent to the enter kind, drag it round to view other places, zoom out and in, and turn between Google’s map, satellite tv for pc, and side road perspectives.

To find the next remark throughout the index.php document:

/var/www/html/digiaddress/index.php

. . .

. . .

Upload the next highlighted code underneath this remark:

/var/www/html/digiaddress/index.php

. . .
        

        
margin-bottom: 15px;">

. . .

Save the document, then talk over with the appliance for your browser once more. You’ll see the next:

As you’ll see, now we have effectively added a map to the appliance. You’ll be able to drag the map round to concentrate on other places, zoom out and in, and turn between the map, satellite tv for pc, and side road perspectives. Having a look again on the code you simply added, realize that now we have additionally added two label controls that can show the geocoordinates and the bodily deal with that had been entered at the kind:

/var/www/html/digiaddress/index.php

            . . .
            
. . .

Talk over with the appliance once more for your browser and input the title of a state within the first box. While you transfer your textual content cursor to the following box, the latitude and longitude labels do not seem, nor does the site proven at the map trade to mirror the ideas you’ve gotten entered. Let’s allow those behaviors.

Step 6 — Including Match Listeners

Including interactive components to an software can lend a hand to stay its customers engaged. We will be able to put into effect a couple of interactive behaviors on this software thru the usage of tournament listeners.

An tournament is any motion that takes position on a internet web page. Occasions may also be one thing carried out through a person or through the browser itself. Examples of not unusual occasions are:

  • Clicking an HTML button
  • Converting the content material of an enter box
  • Converting the point of interest from one web page component to some other

An tournament listener is a directive that tells a program to take a definite motion when a selected tournament takes position. In AngularJS, tournament listeners are outlined with directives that usually observe this structure:

ng-event_type=expression

On this step, we will be able to upload an tournament listener that is helping to procedure the ideas entered through customers right into a mapcode every time they post the shape. We will be able to additionally upload a pair extra tournament listeners that can make the appliance extra interactive. In particular, we will use those listeners to modify the site proven within the software map, position a marker, and draw a rectangle across the location as customers input data into the shape. We will upload those tournament listeners to index.php, so open that document up once more in the event you’ve closed it:

  • nano /var/www/html/digiaddress/index.php

Scroll all the way down to the primary batch of code we added, and to find the block that starts with

. It’ll appear to be this:

/var/www/html/digiaddress/index.php

                . . .
                    
. . .

To start out, upload the next highlighted tournament listener to the outlet

tag. This code tells the app to name the processForm serve as every time a person submits data in the course of the kind. processForm is outlined within the createDigitalAddressApp.js document, and serves as a helper serve as that sends the ideas submitted through customers to the correct recordsdata which then procedure it right into a mapcode. We will be able to take a more in-depth have a look at this serve as in Step 7:

/var/www/html/digiaddress/index.php

                . . .
                    
ng-submit="processForm()" magnificence="custom-form">
. . .

Subsequent, proceed enhancing this block through including a pair blur tournament listeners. A blur tournament happens when a given web page component loses focal point. Upload the next highlighted strains to the kind block's enter tags. Those strains inform the appliance to name the geocodeAddress serve as when a person's focal point shifts clear of the respective kind fields we created in Step 4. Observe that you simply should additionally delete the slashes and greater-than indicators (/>) that shut out every enter tag. Failing to take action will save you the app from registering the blur occasions as it should be:

/var/www/html/digiaddress/index.php

                . . .
                
                            
ng-blur="geocodeAddress(address,'state')" required=""/>
ng-blur="geocodeAddress(address,'zip')" required=""/>
ng-blur="geocodeAddress(address,'town')" required=""/>
ng-blur="geocodeAddress(address,'street')" required=""/>
ng-blur="geocodeAddress(address,'house')" required=""/>
. . .

The primary of those new strains — ng-blur="geocodeAddress(address,'state')" required=""/> — interprets to "When the person's focal point shifts clear of the 'state' box, name the geocodeAddress serve as." The opposite new strains additionally name geocodeAddress, albeit when the person's focal point shifts clear of their respective fields.

As with the processForm serve as, geocodeAddress is said within the createDigitalAddressApp.js document, however there is not but any code in that document that defines it. We will be able to entire this serve as in order that it puts a marker and attracts a rectangle at the software map after those blur occasions happen to mirror the ideas entered into the shape. We will additionally upload some code that takes the deal with data and processes it right into a mapcode.

Save and shut the index.php document (press CTRL+X, Y, then ENTER) after which open thecreateDigitalAddressApp.js document:

  • nano /var/www/html/digiaddress/js/createDigitalAddressApp.js

On this document, to find the next line:

/var/www/html/digiaddress/js/createDigitalAddressApp.js

. . .
$scope.geocodeAddress = serve as (deal with, box) {
. . .

This line is the place we claim the geocodeAddress serve as. A couple of strains underneath this, we claim a variable named fullAddress which constructs a human-readable mailing deal with from the ideas entered through a person into the appliance's kind fields. That is carried out thru a chain of if statements:

/var/www/html/digiaddress/js/createDigitalAddressApp.js

. . .
var fullAddress = "";

    if (deal with ['house']) {
        angular.component(report.getElementById('generate'))[0].disabled = false;
            fullAddress = deal with ['house'] + ",";
                }
    if (deal with ['town']) {
        angular.component(report.getElementById('side road'))[0].disabled = false;
            fullAddress = fullAddress + deal with ['town'] + ",";
    }
    if (deal with ['street']) {
        angular.component(report.getElementById('space'))[0].disabled = false;
            fullAddress = fullAddress + deal with ['street'] + ",";
    }
    if (deal with ['state']) {
        angular.component(report.getElementById('zip'))[0].disabled = false;
            fullAddress = fullAddress + deal with ['state'] + " ";
    }
    if (deal with ['zip']) {
        angular.component(report.getElementById('the city'))[0].disabled = false;
            fullAddress = fullAddress + deal with ['zip'];
    }
. . .

At once after those strains is the next remark:

/var/www/html/digiaddress/js/createDigitalAddressApp.js

. . .
// upload code for finding the deal with on Google maps
. . .

Beneath this remark, upload the next line which exams whether or not fullAddress is any worth instead of null:

/var/www/html/digiaddress/js/createDigitalAddressApp.js

                . . .
                if (fullAddress !== "") {
                . . .

Upload the next code underneath this line. This code submits the ideas entered into the shape to the geoimplement.php document the usage of the HTTP POST method if fullAddress isn't null:

/var/www/html/digiaddress/js/createDigitalAddressApp.js

                    . . .
                    $http({
                        manner: 'POST',
                        url: 'geoimplement.php',
                        records: {deal with: fullAddress},
                        headers: {'Content material-Kind': 'software/x-www-form-urlencoded'}

                    }).then(serve as successCallback(effects) {
                    . . .

Subsequent, upload the next line which exams whether or not the PHP name was once returned effectively:

/var/www/html/digiaddress/js/createDigitalAddressApp.js

                        . . .
                        if (effects.records !== "false") {
                        . . .

If the PHP name was once effectively returned, we will be capable to procedure the end result. Upload the next line, which eliminates any boundary rectangle that can had been formerly drawn at the map through calling the removeRectangle serve as, which is outlined on the most sensible of the createDigitalAddressApp.js document:

/var/www/html/digiaddress/js/createDigitalAddressApp.js

                            . . .
                            removeRectangle();
                            . . .

Underneath the removeRectangle(); line, upload the next 4 strains which is able to create a marker pointing to the brand new location at the map regulate:

/var/www/html/digiaddress/js/createDigitalAddressApp.js

                            . . .
                            new google.maps.Marker({
                                map: locationMap,
                                place: effects.records.geometry.location
                            });
                            . . .

Then upload the next code, which obtains the latitude and longitude data from the end result and shows it with the 2 HTML labels we created within the index.php document in Step 5:

/var/www/html/digiaddress/js/createDigitalAddressApp.js

                            . . .
                            lat = effects.records.geometry.location.lat;
                            lng = effects.records.geometry.location.lng;

                            $scope.deal with.lat = lat;
                            $scope.deal with.lng = lng;

                            geoCoordLabel = angular.component(report.querySelector('#geocoordinates'));
                            geoCoordLabel.html("Geo Coordinate: " + lat + "," + lng);

                            geoAddressLabel = angular.component(report.querySelector('#geoaddress'));
                            geoAddressLabel.html("Geo Address: " + fullAddress);

                            $scope.latlng = true;
                            . . .

Finally, underneath those strains, upload the next content material. This code creates a viewport which marks a brand new boundary rectangle at the map:

/var/www/html/digiaddress/js/createDigitalAddressApp.js

                            . . .
                            if (effects.records.geometry.viewport) {

                                rectangle = new google.maps.Rectangle({
                                    strokeColor: '#FF0000',
                                    strokeOpacity: 0.8,
                                    strokeWeight: 0.5,
                                    fillColor: '#FF0000',
                                    fillOpacity: 0.35,
                                    map: locationMap,
                                    bounds: {
                                        north: effects.records.geometry.viewport.northeast.lat,
                                        south: effects.records.geometry.viewport.southwest.lat,
                                        east: effects.records.geometry.viewport.northeast.lng,
                                        west: effects.records.geometry.viewport.southwest.lng
                                    }
                                });

                                var googleBounds = new google.maps.LatLngBounds(effects.records.geometry.viewport.southwest, effects.records.geometry.viewport.northeast);

                                locationMap.setCenter(new google.maps.LatLng(lat, lng));
                                locationMap.fitBounds(googleBounds);
                            }
                        } else {
                            errorLabel = angular.component(report.querySelector('#lt'));
                            errorLabel.html("Place not found.");
                            $scope.latlng = true;
                            removeRectangle();
                        }

                    }, serve as errorCallback(effects) {
                       console.log(effects);
                    });
                }
                . . .

After including this content material, this segment of the document will appear to be this:

/var/www/html/digiaddress/js/createDigitalAddressApp.js

                . . .
                // upload code for finding the deal with on Google maps
                if (fullAddress !== "") {
                    $http({
                        manner: 'POST',
                        url: 'geoimplement.php',
                        records: {deal with: fullAddress},
                        headers: {'Content material-Kind': 'software/x-www-form-urlencoded'}

                    }).then(serve as successCallback(effects) {

                        if (effects.records !== "false") {
                            removeRectangle();

                            new google.maps.Marker({
                                map: locationMap,
                                place: effects.records.geometry.location
                            });

                            lat = effects.records.geometry.location.lat;
                            lng = effects.records.geometry.location.lng;

                            $scope.deal with.lat = lat;
                            $scope.deal with.lng = lng;

                            geoCoordLabel = angular.component(report.querySelector('#geocoordinates'));
                            geoCoordLabel.html("Geo Coordinate: " + lat + "," + lng);

                            geoAddressLabel = angular.component(report.querySelector('#geoaddress'));
                            geoAddressLabel.html("Geo Address: " + fullAddress);

                            $scope.latlng = true;

                            if (effects.records.geometry.viewport) {

                                rectangle = new google.maps.Rectangle({
                                    strokeColor: '#FF0000',
                                    strokeOpacity: 0.8,
                                    strokeWeight: 0.5,
                                    fillColor: '#FF0000',
                                    fillOpacity: 0.35,
                                    map: locationMap,
                                    bounds: {
                                        north: effects.records.geometry.viewport.northeast.lat,
                                        south: effects.records.geometry.viewport.southwest.lat,
                                        east: effects.records.geometry.viewport.northeast.lng,
                                        west: effects.records.geometry.viewport.southwest.lng
                                    }
                                });

                                var googleBounds = new google.maps.LatLngBounds(effects.records.geometry.viewport.southwest, effects.records.geometry.viewport.northeast);

                                locationMap.setCenter(new google.maps.LatLng(lat, lng));
                                locationMap.fitBounds(googleBounds);
                            }
                        } else {
                            errorLabel = angular.component(report.querySelector('#lt'));
                            errorLabel.html("Place not found.");
                            $scope.latlng = true;
                            removeRectangle();
                        }

                    }, serve as errorCallback(effects) {
                       console.log(effects);
                    });
                }
                . . .

Save the document, however stay it open for now. For those who had been to talk over with the appliance for your browser once more, you would not see any new adjustments to its look or habits. Likewise, in the event you had been to go into an deal with and click on at the Generate button, the appliance nonetheless would now not generate or show a mapcode. It is because we should nonetheless edit a couple of recordsdata sooner than the mapcode capability will paintings. Let's proceed to make those adjustments, and in addition take a more in-depth have a look at how those mapcodes are generated.

Step 7 — Figuring out Mapcode Technology

Whilst nonetheless having a look on the createDigitalAddressApp.js document, scroll previous the segment of code that you simply added within the earlier step to search out the code that takes the ideas submitted in the course of the kind and procedure it into a novel mapcode. Each time a person clicks the Generate button, the code throughout the index.php document submits the shape and calls the processForm serve as, which is outlined right here in createDigitalAddressApp.js:

/var/www/html/digiaddress/js/createDigitalAddressApp.js

. . .
$scope.processForm = serve as () {
. . .

processForm then makes an HTTP POST to the generateDigitalAddress.php document:

/var/www/html/digiaddress/js/createDigitalAddressApp.js

. . .
$http({
    manner: 'POST',
    url: 'generateDigitalAddress.php',
    records: $scope.deal with,
    headers: {'Content material-Kind': 'software/x-www-form-urlencoded'}
}).then(serve as (reaction) {
. . .

The Stichting Mapcode Foundation supplies the API that generates mapcodes from bodily addresses as a unfastened internet provider. To know how this name to the Mapcode internet provider works, shut createDigitalAddressApp.js and open the generateDigitialAddress.php document:

  • nano /var/www/html/digiaddress/generateDigitalAddress.php

On the most sensible of the document, you can see the next:

/var/www/html/digiaddress/generateDigitalAddress.php

The road studying come with("db.php"); tells PHP to come with the entire textual content, code, and markup from the db.php document throughout the generateDigitalAddress.php document. db.php holds the login credentials for the MySQL database you created in Step 2, and through together with it inside generateDigitalAddress.php, we will be able to upload any deal with data submitted in the course of the kind to the database.

Beneath this come with remark are a couple of extra strains that download the latitude and longitude data according to the request submitted through createDigitalAddressApp.js:

/var/www/html/digiaddress/generateDigitalAddress.php

. . .
$records = json_decode(file_get_contents("php://input"));
$lat = $data->lat;
$lengthy = $data->lng;
. . .

Search for the next remark in generateDigitalAddress.php document.

/var/www/html/digiaddress/generateDigitalAddress.php

. . .
// name to mapcode internet provider
. . .

Upload the next line of code underneath this remark. This code makes a decision the Mapcode API, sending lat and lengthy as parameters.

/var/www/html/digiaddress/generateDigitalAddress.php

. . .
// name to mapcode internet provider
$digitaldata = file_get_contents("https://api.mapcode.com/mapcode/codes/".$lat.",".$lengthy."?include=territory,alphabet&allowLog=true&client=web");
. . .

The internet provider returns the JSON records which was once assigned to digitaldata, and the next remark decodes that JSON:

/var/www/html/digiaddress/generateDigitalAddress.php

. . .
$digitalAddress["status"] = json_decode($digitaldata, TRUE)['local']['territory']." ".json_decode($digitaldata, TRUE)['local']['mapcode'];
. . .

This returns a mapcode for the user-specified location. The next strains then retailer this knowledge within the database:

/var/www/html/digiaddress/generateDigitalAddress.php

. . .
$obj = new databaseConnection();

$conn = $obj->dbConnect();

$obj->insertLocation($conn, $digitalAddress["status"],$data->state,$data->zip,$data->side road,$data->the city,$data->space,$lat,$lengthy);
. . .

Then, the overall line echoes the mapcode again to the caller serve as:

/var/www/html/digiaddress/generateDigitalAddress.php

. . .
echo json_encode($digitalAddress);

Save and shut this document, then reopen createDigitalAddressApp.js once more:

  • nano /var/www/html/digiaddress/js/createDigitalAddressApp.js

When a mapcode has been retrieved effectively, the next strains within the createDigitalAddressApp.js document shows it to the person in a conversation field:

/var/www/html/digiaddress/js/createDigitalAddressApp.js

. . .
digiAddress = reaction.records.standing;
. . .
$('#digitalAddressDialog').modal('display');
. . .

Even though you probably did upload a brand new line of code to generateDigitalAddress.php, you continue to may not see any practical adjustments whilst you talk over with and engage with the app for your browser. It is because you've gotten now not but added your Google API key to the geoimplement.php document, which makes the real name to the Google Maps API.

Step 8 — Enabling Calls to the Google Maps API

This software is determined by the Google Maps API to translate a bodily deal with into the correct latitude and longitude coordinates. Those are then handed directly to the Mapcode API which makes use of them to generate a mapcode. Because of this, if the appliance is not able to keep in touch with the Google Maps API to generate the site's latitude and longitude, any try to generate a mapcode will fail.

Recall from Step 6 the place, after setting up the deal with records, we handed the end result alongside by means of an HTTP POST request within the createDigitalAddressApp.js document:

/var/www/html/digiaddress/js/createDigitalAddressApp.js

$http({
    manner: 'POST',
    url: 'geoimplement.php',
    records: {deal with: fullAddress},
    headers: {'Content material-Kind': 'software/x-www-form-urlencoded'}
}).then(serve as successCallback(effects) {

This code block sends the deal with records entered through a person to the geoimplement.php document which accommodates the code that calls the Google Maps API. Pass forward and open this document:

  • nano /var/www/html/digiaddress/geoimplement.php

You can see that it first decodes the deal with that was once won in the course of the POST request:

/var/www/html/digiaddress/geoimplement.php

. . .
$records=json_decode(file_get_contents("php://input"));
. . .

It then passes the deal with box of the enter records to a geocode serve as which returns the geographic data at the deal with:

/var/www/html/digiaddress/geoimplement.php

. . .
$outcome = geocode($data->deal with);
. . .

The result's then echoed again to the caller:

/var/www/html/digiaddress/geoimplement.php

. . .
echo json_encode($outcome);
. . .

The geocode serve as encodes the deal with and passes it directly to the Google Maps API, together with your software key:

/var/www/html/digiaddress/geoimplement.php

. . .
// url encode the deal with
$deal with = urlencode($deal with);

// google map geocode api url
$url = "https://maps.googleapis.com/maps/api/geocode/json?deal with={$deal with}&key=";
. . .

Ahead of scrolling on, pass forward and upload your API key to the road underneath the // google map geocode api url remark:

/var/www/html/digiaddress/geoimplement.php

. . .
// google map geocode api url
$url = "https://maps.googleapis.com/maps/api/geocode/json?deal with={$deal with}&key=ExampleAPIKeyH2vITfv1eIHbfka9ym634Esw7u";
. . .

After sending the decision to the Google Maps API, the reaction is decoded and its worth is returned through the serve as:

/var/www/html/digiaddress/geoimplement.php

. . .
// get the json reaction
$resp_json = file_get_contents($url);

// decode the json
$resp = json_decode($resp_json, true);

if ($resp['status'] == 'OK') {
    go back $resp['results'][0];
} else {
    go back false;
}
. . .

Save this document, and talk over with your software as soon as once more. Enter US-NY within the state box after which hit TAB to modify the enter focal point to the following box. You'll see the next output:

Realize that the geocoordinates and bodily deal with that you simply entered within the kind seem beneath the map. This makes the appliance really feel a lot more enticing and interactive.

Observe: In the case of abbreviations for position names, Mapcode makes use of the ISO 3166 usual. Because of this it would possibly not interpret some commonly-used abbreviations as anticipated. As an example, if you would like to generate a Mapcode for an deal with in Louisiana and also you input LA, the map will bounce to Los Angeles, California (slightly than the state of Louisiana).

You'll be able to keep away from confusion with US postal abbreviations through previous them with US-. Within the context of this Louisiana instance, you could input US-LA.

To be told extra about how Mapcode makes use of this usual, take a look at the Territories and standard codes reference page.

In spite of this development to how the appliance shows places at the map, the app nonetheless is not absolutely practical. The final step you wish to have to take sooner than you'll generate a mapcode is to edit the db.php document to permit the appliance to get right of entry to your database.

Step 9 — Including Database Credentials and Trying out Mapcode Technology

Recall that this software retail outlets each and every deal with entered into the shape — together with its latitude, longitude, and mapcode — within the database you created in Step 2. That is made imaginable through the code throughout the db.php document, which retail outlets your database credentials and lets in the appliance to get right of entry to the places desk inside it.

As a last step to allow the mapcode era capability, open the db.php document for enhancing:

  • nano /var/www/html/digiaddress/db.php

Close to the highest of this document, to find the road that starts with $move. This line submits your MySQL login credentials with the intention to permit the appliance to get right of entry to your database. Change your_password together with your root MySQL person's password:

/var/www/html/digiaddress/db.php

. . .
        $username = "root";
        $move = "your_password";
. . .

That's the final trade you wish to have to make with the intention to generate a mapcode from a bodily deal with. Save and shut the document, then pass forward and refresh the appliance for your browser as soon as once more. Input in an deal with of your selection and click on the Generate button. The output will glance very similar to this:

At this level, you've finished your software and you'll now generate a quick virtual deal with for any bodily location on the planet. Be happy to experiment with other addresses, and observe that the deal with you input does now not essentially want to be inside america.

Your ultimate job is to allow this app's 2d capability: retrieving an deal with from the database the usage of its respective mapcode.

Step 10 — Retrieving a Bodily Cope with

Now that you are ready to generate a mapcode from a given bodily deal with, your ultimate step is to retrieve the unique bodily deal with, as derived from the mapcode. To perform this, we will be able to broaden a PHP person interface, proven right here:

The code for this UI is to be had within the findaddress.php document. Because the UI outlined inside this document is reasonably very similar to the UI we coated previous in Step 4, we will be able to now not glance too carefully at the entire main points of the way it works. We will be able to, on the other hand, undergo those 3 recordsdata to give an explanation for usually how they serve as.

To be able to allow the deal with retrieval capability, you can want to upload your Google API key to the findaddress.php document, so open it up together with your most popular editor:

  • nano /var/www/html/digiaddress/findaddress.php

Close to the ground of the document, to find the road that starts with

/var/www/html/digiaddress/findaddress.php

%MINIFYHTMLad3eacf13278a724d2870e5e81d0c9ac9%

Change together with your Google API key as you've gotten carried out within the earlier steps, then save the document. Ahead of last it, even though, let's take a handy guide a rough glance to look how those recordsdata paintings in combination.

When a person submits the shape it triggers a post tournament, and an tournament listener calls the fetchadd serve as:

/var/www/html/digiaddress/findaddress.php

. . .
. . .

The fetchadd serve as sends the virtual deal with to fetchaddress.php with a POST request:

/var/www/html/digiaddress/js/findAddressApp.js

. . .
$http({
    manner : 'POST',
    url : 'fetchaddress.php',
    records : {digiaddress: $scope.digiaddress}
}).then(serve as(reaction){
. . .

If the POST is a success, the serve as returns a JSON reaction. The next line parses this reaction:

/var/www/html/digiaddress/js/findAddressApp.js

. . .
var jsonlatlng = JSON.parse(reaction.records.latlng);
. . .

The following strains set the marker at the map:

/var/www/html/digiaddress/js/findAddressApp.js

. . .
marker = new google.maps.Marker({
    place: new google.maps.LatLng(jsonlatlng.latitude, jsonlatlng.longitude),
        map: locationMap
});
. . .

And the next prints the geocoordinates and the bodily deal with:

/var/www/html/digiaddress/js/findAddressApp.js

. . .
geoCoordLabel = angular.component(report.querySelector('#geocoordinates'));
geoCoordLabel.html("Geo Coordinate: "+ jsonlatlng.latitude +","+ jsonlatlng.longitude);

geoAddressLabel = angular.component(report.querySelector('#geoaddress'));
geoAddressLabel.html("Geo Address: " + jsonlatlng.space +","+ jsonlatlng.the city +","+ jsonlatlng.side road +","+ jsonlatlng.state + " " + jsonlatlng.zip );
. . .

Talk over with this software for your browser through going to the next hyperlink:

http://your_server_ip/digiaddress/findaddress.php

Check it out through getting into within the mapcode you received previous. The next determine displays an ordinary output:

With that, your software is done. You'll be able to now create a novel mapcode for any location on the planet, after which use that mapcode to retrieve the site's bodily deal with.

Conclusion

On this educational you used the Google Maps API to pin a location and will get its longitude, latitude data. This knowledge is used to generate a novel and quick virtual deal with the usage of Mapcode API. There are a selection of sensible use circumstances for mapcodes, starting from emergency services and products to archaeological surveying. The Stichting Mapcode Foundation lists a number of such use circumstances.

Acknowledgements

Many due to Dinesh Karpe and Sayli Patil for creating all of the mission code.