Example 1 – HTML5 location powered by Google Maps

In this example, we will expand the Google Maps integration example from Chapter 4, Libraries, so that there will be a new option of showing the user where they are located on the Google Map. For doing so, we will use the HTML5 navigator.geolocation service to request the browsing user to share its location with the application. If the user agrees, and is using an advanced browser, such as the latest Firefox, Chrome builds that support to this service. Once we get the values, we will collect the geolocation, and call a controller method to prepare the Google Map of that area to render a Google Map view with the option navigator. We will use the HTML5 navigator.geolocation service as follows:

navigator.geolocation.getCurrentPosition(getLocation, locationFail);

Here, getLocation is called, if the location was successfully fetched, and locationFail, if it was failed.

We will start with the controller first.

The controller file

The controller PHP file is located at application/controllers/gmaps.php. The following is the controller code based on Chapter 4, Libraries, for the extended Google Maps API integration example, where the new parts of code are highlighted:

class Gmaps extends CI_Controller
{
// Extends the CI controller to be our Gmaps controller powered by 
// the Google API wrapper library.
  // Setting the initialization parameters of Google Maps 
  // Library Mapper for the window size where the 
  // user interaction with Google Maps created window will occur
  private $user_lon = 0;
  private $user_lat = 0;
  function __construct()
  {parent::__construct();
    $this->load->library('googlemaps'),
    // Set the map window sizes:
    $config['map_width'] = "1000px";  // map window width
    $config['map_height'] = "1000px";  // map window height
    $this->googlemaps->initialize($config);
  }
  function index()
  {
  /*Initialize and setup Google Maps for our App starting with 3 marked places: London, UK, Bombai, India, Rehovot, Israel */
  // Initialize our map for this use case of show 3 places // altogether.
  // let the zoom be automatically decided by Google for// showing the several places in one view
  $config['zoom'] = "auto";
  $this->googlemaps->initialize($config);
  //Define the places we want to see marked on Google Map!
  $this->add_visual_flag ('London, UK'),
  $this->add_visual_flag ('Bombai, India'),
  $this->add_visual_flag ('Rehovot, Israel'),
  
  // **NEW CODE ** 
  // optional user location if user allow it and was fetched// successfully
  if ( $this->is_user_location_defined () ) {
    $this->add_visual_flag ($this->get_user_location ());
  }
  
  $data = $this->load_map_setting ();
  // Load our view, passing the map data that has just been //created.
  $this->load->view('google_map_view', $data);
}
// ** NEW CODE **
function user_location ($lat=0, $lon=0)
{
  // This is a new code we add for showing the //Geolocation fetched from the view base HTML5 Geolocation//service.
  //Initialize our map with it if it is set.
  if (! $lat&& ! $lon ) $this->index();
  
  // They are ok - let's keep them 
  $this->user_lat = $lat;
  $this->user_lon = $lon;
  $config['center'] = $this->get_user_location ();
  // Define the address we want to be on the map center
  $config['zoom'] = "5";
  // since its approximate location is country level
  $this->googlemaps->initialize($config);
  //Add visual flag
  $this->add_visual_flag ($config['center']);
  $data = $this->load_map_setting ();
  // Load our view, passing the map data that has just been //created.
  $this->load->view('google_map_view', $data);
  }
// ** NEW CODE
functionis_user_location_defined ( ) {
  return ( $this->user_lat != 0 ) || ( $this->user_lon!= 0 );
  }
// ** NEW CODE
functionget_user_location ( ) {
  return $this->user_lat.", ".$this->user_lon;
  }

functionlondon() 
{
  // as before
  }

functionbombai()
{
  // as before
  }
functionrehovot()
{
  // as before
  }
functionload_map_setting ( ) {
  // as before
  }
functionadd_visual_flag ( $place ) {
  // as before
  }
}
//End class Gmaps

The view file

The view PHP file is located at application/views/google_map_view.php.The following is the view file code based on Chapter 4, Libraries, for the extended Google Maps API usage example view, where the new parts of code are highlighted.

Here, we add an HTML5 service in JavaScript to collect the user's geolocation, and call the controller method user_location ($lat=0, $lon=0).

<!DOCTYPE html">
<meta http-equiv="Content-type" content="text/html;charset=utf-8" />
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js" type ='text/javascript'></script>
<script>
// New Code to get the user Geolocation and ask the controller to// render a Google Map for it.
var latitude = 0;
var longitude = 0;
functionshow_on_map () {
  var DIRECTORY_SEPARATOR = '/';
  
  // Prepare the URL path of calling the Gmaps controller method// user_location with latitude and longitude coordinates as// parameters using the CI naming convention of
  // ControllerName/methodName/Param1/Param2
  Var url_to_show = 
  '<?php echo base_url(); ?>index.php/gmaps/user_location/' +
  longitude + DIRECTORY_SEPARATOR + latitude;
  // Use jQuery to issue the HTTP controller call and rendering// request
  $(location).attr('href', url_to_show );
  }
$(document).ready(function() {
  // if user clicks on the <li> for getting its Geolocation
  $('#getmylocation').click(checkLocation);
  functioncheckLocation() {
    // Check if the browser supports the HTML5 Geolocation
    // Note that navigator.geolocation will pop a request from// the user to allow getting its location (Privacy)
    if (navigator.geolocation) {
      // It does so let the user be notified
      $('#notifications').html ( 'fetching your location, wait...' );
      $('#notifications').css ( 'color', 'blue' );
      
      // Try to fetch the latitude/longitude of the browsing user//and provides the callbacks
      // Success: getLocation
      // Failure: locationFail
      navigator.geolocation.getCurrentPosition(getLocation, locationFail);
    }
    
else {
      $('#notifications').html( 'Sorry, your browser settings does not enable fetching yourGeolocation'),
    } // ends checkLocation()
    //this is what happens if getCurrentPosition is successful
    functiongetLocation(position) { 
      latitude = position.coords.latitude;
      longitude = position.coords.longitude;
      // Notify user for its location:
      $('#notifications').html
      ( 'Your approx. position : (' + latitude + ',' + longitude + ')' );
      $('#notifications').css ( 'color', 'green' );
      // Two seconds after the notification to user we have the// location issue call to the controller to show it on// the Google Map
      setTimeout ( show_on_map, 2000);
      }
    //this is what happens if getCurrentPosition is unsuccessful//(getCurrentPositionerrorCallback)
    functionlocationFail() {
      $('#notifications').html('Sorry, your browser could not fetch your location ...'),
      $('#notifications').css ('color', 'red'),
      }
    });
    </script>
    <!—As Before..  -->
    <!—Notification selector  -->
    <HR></HR>
    <DIV style='background:lightgreen;width:300px;'>
    <span id='notifications'>...</span>
    </DIV>
    <HR></HR>
    <ul>
    <!-- Let the User Always Get Back to the default Zoom out withall places marked>
    <li><?php echo anchor("index.php/gmaps", '<B>See All Locations</B>' ) ?></li>
    <!—If user clicks this one the Geo Location service will start -->
    <li id = 'getmylocation' style = 'cursor: pointer;color: blue; decoration: underline'> Show Me My Location</li>
    <!—As Before..  -->
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.137.217.95