Locate an Address using Geocoding

Very popular in many web and mobile applications today is the ability to locate an address on a map. In this post you will learn to use the google maps API to do just this. Create a new HTML page and add jQuery and Bootstrap to the page so it resembles the HTML shown below.

<!DOCTYPE html>
<html>
<head>
  <title>Geocode Sample</title>
  <link href="../Content/bootstrap.min.css" rel="stylesheet" />
  <style>
    #theMap {
      width: 100%;
      height: 600px;
    }
  </style>
</head>
<body>
  <div class="container">
    <div class="row">
      <div class="col-xs-12">
        <h1>Geocode Address</h1>
      </div>
    </div>
    <div class="form-group">
      <label for="address">Address</label>
      <input id="address"
             type="text"
             class="form-control"
             value="17852 17th Street, Tustin CA 92780" />
    </div>
    <div class="form-group">
      <button id="search"
              class="btn btn-sm btn-primary"
              onclick="controller.searchClick();">
        Search
      </button>
    </div>
    <div class="row">
      <div class="col-xs-6">
        <div class="form-group">
          <label for="lat">Latitude</label>
          <input id="lat"
                 type="number"
                 class="form-control"
                 value="0" />
        </div>
      </div>
      <div class="col-xs-6">
        <div class="form-group">
          <label for="long">Longitude</label>
          <input id="long"
                 type="number"
                 class="form-control"
                 value="0" />
        </div>
      </div>
    </div>
    <div class="row">
      <div class="col-xs-12">
        <div id="theMap"></div>
      </div>
    </div>
  </div>
  <script src="../scripts/jquery-1.11.0.min.js"></script>
  <script src="../scripts/bootstrap.min.js"></script>
</body>
</html>


Notice the additional <style> tag in the <head>. This is used to style the <div> tag that will display the google map. <div> tags are defined with a height of zero, so if you don't add at least a height, your map will not show up.

Add the following script tag for the google map API just below the bootstrap.min.js script tag.

<script src="https://maps.googleapis.com/maps/api/js?v=3&sensor=false&libraries=geometry"
        type="text/javascript">
</script>


Create a JavaScript Closure

Define a JavaScript closure to hold all of the logic for our page. The code snippet below shows the overall structure of the closure without the details of each function. We will cover the details a little later. Notice that this closure is assigned to a variable named 'controller'. You will see this referenced in the onclick attribute of the Search button shown above in the HTML.

<script>
  var controller = (function () {
    // Declare Private Variables
    var map = null;
    var location = null;
    var lat = 0;
    var long = 0;
    var address = '';
    var mapId = 'theMap';
    var markerIcon = 'http://maps.google.com/mapfiles/ms/icons/blue-dot.png';
    // ************************************
    // Private Functions
    // ************************************
    // Display messages
    function display(msg) {
      alert(msg);
    }
    // Search for address
    function searchForAddress() {
    }
    // Initialize map
    function initMap() {
    }
    // Add marker to map
    function setMarker(pos, title) {
    }
    
    // Update any UI elements
    function updateUI() {
    }
    // ************************************
    // Public Functions
    // ************************************
    return {
      searchClick: function () {
        address = $("#address").val();
        searchForAddress();
      },
      setMapId: function (id) {
        mapId = id;
      },
      setMarkerIcon: function (icon) {
        markerIcon = icon;
      }
    };
  })();
</script>


Private Variables

At the top of the closure is where you declare private variables needed for geocoding and to hold values retrieved from the web page or to put back onto the web page.

'map' - a reference to the google map object. 

'location' - a LatLng object. 

'lat' and 'long' - numeric values that hold the latitude and longitude respectively.

'address' - a street address to locate. 

'mapId' - the id of the <div> where you wish to place the map. 

'markerIcon' - the icon to use for the map marker.


Private Functions

Private functions defined in the closure are used to do searching, create the google map object, set map markers and update the web page UI with any data.

display() - display any messages to the user.

searchForAddress() - search for the street address and if found will set the 'lat' and 'long' variables, display the map, and display a marker on the map at the location of the found address.

initMap() - creates the google map and displays it on the web page.

setMarker() - adds a marker to the map at the specified coordinates.

updateUI() - update any fields or other elements on your page.


Public Functions

Public functions are created so you can call private functions from your web page.

searchClick() - get the address to search for from the input and calls the searchForAddress() function.

setMapId() - allows you to change the id of the element to place your map upon.

setMarkerIcon() - allows you to change the icon to use as your map marker.


The searchForAddress() Function

The searchForAddress() function locates a physical address and sets the 'lat' and 'long' variables so you can display a marker of where the address is located on a map. An instance of a google.maps.Geocoder object has methods for performing geocoding. Call the geocode() function of the Geocoder object passing in an object literal with the string 'address' and the actual address to locate. This is an asynchronous call, so you need to supply a call back function. This function needs two parameters; 'result' and 'status'. You check the 'status' to ensure that you received an OK. If you receive an OK status, check the 'results' array at element 0 to get the address information.

Within the 'results[0]' element is a geometry object which contains a location. Call the lat() function to retrieve the latitude for the address and set the 'lat' variable. Call the lng() function to retrieve the longitude for the address and set the 'long' variables. Once these variables are set, call the initMap() function to create a map using these coordinates as the center point. Call the setMarker() function to place a map on the specified coordinates. Finally, call updateUI() to display the latitude and longitude in the appropriate fields on the web page. There are several other status codes that can be returned from the geocode() function, so you should give the user an appropriate messages based on that status.

function searchForAddress() {
  var geocoder = new google.maps.Geocoder;
  if (address.length > 0) {
    geocoder.geocode({ 'address': address }, function (results, status) {
      switch (status) {
        case google.maps.GeocoderStatus.OK:
          if (results[0]) {
            // Get latitude
            lat = results[0].geometry.location.lat();
            // Get longitude
            long = results[0].geometry.location.lng();
            // Initialize the map
            initMap();
            // Set marker on map
            setMarker(location, address);
            // Update the UI
            updateUI();
          }
          else {
            display("Could not locate address.");
          }
          break;
        case google.maps.GeocoderStatus.ZERO_RESULTS:
          display("No such address found.");
          break;
        case google.maps.GeocoderStatus.OVER_QUERY_LIMIT:
          display("Query limit has been exceeded.");
          break;
        case google.maps.GeocoderStatus.REQUEST_DENIED:
          display("Query request was denied.");
          break;
        case google.maps.GeocoderStatus.INVALID_REQUEST:
          display("Query request was invalid.");
          break;
        default:
          display("Unknown status: " + status);
          break;
      }
    });
  }
  else {
    display("Please enter an address.")
  }
}


The initMap() Function

The initMap() function creates a new LatLng object using the variables 'lat' and 'long' in the closure. Create an object literal with the properties 'center', 'zoom', and 'mapTypeId'. Set 'center' to the new LatLng object. Set 'zoom' to the size of the map you wish to display. You may need to play with this number a bit to see what size you prefer. The 'mapTypeId' is a constant defined by google. You can choose the most common option, ROADMAP, or set it to SATELLITE, TERRAIN or HYBRID.

function initMap() {
  location = new google.maps.LatLng(lat, long);
  var options = {
    center: location,
    zoom: 15,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };
  map = new google.maps.Map(document.getElementById(mapId), options);
}


The setMarker() Function

After the map is drawn, add a map marker by calling the setMarker() function. This function creates a Marker object by passing in an object literal with the properties 'position', 'map', and 'title'. The 'position' is the LatLng object you created in initMap(). 'map' is the map object you created in initMap(). The title can be anything you want to appear when you hover over the map marker.

function setMarker(pos, title) {
  var marker = new google.maps.Marker({
    position: pos,
    map: map,
    title: title
  });
  marker.setIcon(markerIcon);
}


The updateUI Function

I prefer to keep all updates to my UI in as few functions as possible. So, I create a updateUI() function that updates any fields on my page with the values from my private variables.

function updateUI() {
  $("#lat").val(lat);
  $("#long").val(long);
}


Summary

In this blog post you learned how to map a physical address to a latitude and longitude and display that address on a map. You can get more information at https://developers.google.com/maps/. If you would like help with any #geocoding projects, please call #PDSAinc at (714) 734-9792 to discuss your project.


Locate your IoT Device using Geocoding

Many applications today have a need to show the user where they are, direct them to a specific location, or maybe show the location of a certain asset. In a #IoT application we are currently developing, we have a device that sends us its latitude and longitude. From this we want to display this information on a map so our user can quickly locate that asset. Performing this task is very easy using the google maps API (#googlemaps). Let's take a look at the small amount of code you need to add to any HTML page.

First add a <div> tag at the location on your page where you wish to place the map.

<div id="theMap"></div>

Now add a little styling to the map

<style>
  #theMap {
    width: 600px;
    height: 600px;
  }
</style>

Next, include the appropriate script file for the google API.

<script src="http://maps.google.com/maps/api/js?sensor=true"
        type="text/javascript">
</script>

All you need now are your latitude and longitude from your IoT device, which I have hard coded in the code below.

(function () {
  // Private Variables
  var map = null;
  var lat = 33.758432;
  var long = -117.820738;
  var mapID = "theMap";   // Initialize the map   initMap();   function initMap() {   var startLoc = new google.maps.LatLng(lat, long);     var mapOptions = {       center: startLoc,       zoom: 15,       mapTypeId: google.maps.MapTypeId.ROADMAP     };     map = new google.maps.Map(document.getElementById(mapID), mapOptions);   } })();

The function initMap() first gets a LatLng object from the google maps API. You could use a LatLng literal object instead, but I want to reuse this LatLng object later in my code to place a marker, so I will create the object. Next you create a map options object that tells the center point using your LatLng object. You may specify a zoom level that you want. You will have to play with this number to get the zoom level you want as the default. There are a few different types of maps you can display. The most common one is the road map, which is specified by using the ROADMAP constant. Finally you send a reference to the <div> element and the map options object to the Map() function of the google API. This will draw the map into your <div> element.

If you run the page, you should see a map appear over the city of Tustin, CA. This is where the PDSA offices are located. If you wish to place a map marker over the location, add the following code after the call to the google.maps.Map() function.

var marker = new google.maps.Marker({
  position: startLoc,
  map: map,
  title: 'PDSA'
}); marker.setIcon('http://maps.google.com/mapfiles/ms/icons/blue-dot.png');

That is all there is to starting to use the google API geolocation services in your application. You can get more information at https://developers.google.com/maps/.


As always, if you need help implementing any of the concepts in our posts, please feel free to reach out to #PDSAinc and we will be happy to help.

PDSA Presents at DevIntersection April 18-21, Florida (Disney Swan Hotel)

PDSA will be presenting several great sessions at the DevIntersection Conference to be held at the Disney Swan Hotel April 18-21.

The following sessions will be presented:

  • Do More Client-Side with JSON, 4/19/2016 - Paul Sheriff
  • Consolidate MVC Views using SPA Technique,s 4/19/2016 - Paul Sheriff
  • Project Planning for Software Engineers, 4/20/2016 - Michael Krasowski
  • Project Control for Software Engineers, 4/21/2016 - Michael Krasowski
  • Effective Leadership & Comm. for Software Eng., 4/21/2016 - Michael Krasowski

To learn more about DevIntersection, click HERE.

Poor up-front Definition of Requirements Is One of the Major Causes of Failed Software

Yes, that's a fact! When the activity of defining requirements is either skipped or poorly performed, the resulting application software just does not meet your customer's requirements.

Successful software development is often hindered by:

  1. The poor state of the process of requirements analysis. Most organizations do not have any rigor or process to gather requirements, resulting in vague imprecise requirements.
  2. The artifacts that make up the requirements (i.e. documentation). The results of the analysis (AKA artifacts) are thrown together and not easy to read or follow.
  3. The ability of the business analyst(s). Not everyone is cut out to be an analyst. It can take great skill in understanding the business, working with customers and knowing the technical inclinations.

The business analyst or consultant must also address and understand:

  1. Who will be the real system users?
  2. What are users' needs and expectations?
  3. How well is the problem domain understood?
  4. How rigorously, accurately and succinctly are the requirements captured in the specification document?

So, if you need help...we are here for you.

To learn more about PDSA's services, click HERE.




Paper is Gone! New App Allows Yacht Maintenance from Tablet

Checklist Project
Luxury yachts require a significant amount of regularly scheduled maintenance to keep running smoothly and safely, and to maintain compliance. The Checklist app keeps track of the various maintenance intervals and due dates and also provides a means to identify and assign failures or non-conformities to rectify any found issues.
PDSA was called in to upgrade their current system and to provide an application which helps crew members complete these checklists. As the inspectors go into and around areas of the yacht that may not have internet access, they are able to perform their inspections and update the information once they reach wireless access to their network.

To read more of our case study, click  HERE.

New App Eliminates Spreadsheets, Increases Sales

Vehicle Order System
Prior to the Vehicle Order System, dealers filled in spreadsheets and submitted them to
to the Corporation to place the orders.

PDSA created system features which include a front-end process for dealers to enter and place orders by
product segment, model and color level, along with a back-end process for staff
to set up and initiate an order period.
At the end of the order period, the management team are able to access business
intelligence features to assess order activity by region, district, and dealer.

Business Value
The Vehicle Order System enabled them to reduce the order period from every 6 months to every 2 months. This helped reduce unwanted/excess inventory, reduced over-ordering and helped streamline the manufacturing cycle.

To read more of our case study, click HERE.

Portal Gives Partners Ability to See Order Status

Merchant Portal
The Merchant Portal application is a website that merchant partners can use to order and download discount and value codes. Users can also receive order status, review invoices, and view existing codes. Users can administer merchant accounts, and process merchant orders.

Business Value
Merchant Portal streamlines a process that is currently manual and labor-intensive, thus reducing labor hours and eliminating potential lost information, while providing a record of the state of each request and allowing the merchant to access current information as well as past history.

To read more of our case study, click HERE.

Giving Executives What They Need with a Personal Dashboard

PDSA was contracted to build many applications for various departments within a company. As more information is brought into the centralized database, we are able to provide metrics for their executive decision support on the related data and to give a dashboard overview at any point in time. To achieve these snapshot views, we took advantage of the various tools in Microsoft’s SQL Server Reporting Services – Pie charts, multiple series Bar Charts, and table Matrices (Pivot tables).

To read more of our case study, click HERE.


Eliminated Manual Process by Using Modern Web API's

A new online ordering system was created for customers to order products and have
them shipped directly to their home or to their local dealer. This new ordering system
used a third-party ordering system that took care of moving the orders through various
states and handled credit card payments. This third-party had a REST API that can be
called to retrieve order information. All of this information needed to be retrieved and
pushed to their in-house mainframe system.

PDSA was called in to develop this rather complex system. Our job was to integrate with the third party order processor via Web API calls, integrate with another third party vendors Web API to calculate sales tax, and integrate with their mainframe.

The new system allows the Company to offer their customers and their dealers a streamlined order process that can be done completely on the web. Ordering, shipping details and the ability to process returns are now completely automated via their website.

To read more of our case study, click HERE.

Application Streamlines Obama Care for Employers, Saving Time and Money

Online Enrollment Project (PRO Enroll)

PRO Enroll is a public website that allows groups to conduct their annual open enrollment online. Using a link provided by their enrollment coordinator, employees can self-register on the site. Once registered, they enter their personal information and make their insurance selections from the plans offered to their group. Each plan offering has detailed benefit and pricing information to assist the employee in making their selection. Once the employee has made their selections, they proceed to the application step to complete their enrollment.

PDSA was called in to develop this rather complex system. Our job was to develop this new site, while integrating with Warner Pacific’s existing processes and applications.

To read more of our case study, click HERE.