Login | Sign up | Toll-Free: 1-800-752-0455
 
 

Forum

 

3 posts by 2 authors in: Forums > Off Topic / Other
Last Post: September 18, 2017

Has anyone tried using HTML5 Geo Location to power Geocoder's Proximity Search?

Here's a bit of example code of geolocation:

https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/Using_geolocation

<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Geolocation Example</title>
</head>

<body>
<p>Sourced: <a href="https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/Using_geolocation">https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/Using_geolocation</a></p><br><br>

<p><button onclick="geoFindMe()">Show my location</button></p>
<div id="out"></div>

<script type="text/javascript">
function geoFindMe() {
  var output = document.getElementById("out");

  if (!navigator.geolocation){
    output.innerHTML = "<p>Geolocation is not supported by your browser</p>";
    return;
  }

  function success(position) {
    var latitude  = position.coords.latitude;
    var longitude = position.coords.longitude;

    output.innerHTML = '<p>Latitude is ' + latitude + '° <br>Longitude is ' + longitude + '°</p>';

    var img = new Image();
    img.src = "https://maps.googleapis.com/maps/api/staticmap?center=" + latitude + "," + longitude + "&zoom=13&size=300x300&sensor=false";

    output.appendChild(img);
  }

  function error() {
    output.innerHTML = "Unable to retrieve your location";
  }

  output.innerHTML = "<p>Locating…</p>";

  navigator.geolocation.getCurrentPosition(success, error);
}
</script>

</body>
</html>

Wondering if this can be accomplished.

Zicky

Hi Zicky, 

For any of the GeoCoder search forms, such as the example form: 

  • Plugins > GeoCoder > Example Code > Proximity search with results sorted by distance

You can specify the "fromAddress" as Latitude, Longitude with a comma in the middle, eg: 49.282729,-123.120738

So you could make a button that requested the users current location from the navigator.geolocation browser API and then set the value of the fromAddress to their Lat,Lng coordinates.

Hope that helps!

Dave Edis - Senior Developer
interactivetools.com

Thanks for the guidance Dave,

I tooled around with this a little and got it working. Not going to say it's the cleanest solution, but it's working and that's a start. Not so sure about the line in bold ( <?php echo (@$_REQUEST['fromAddress'] = $gotGeo); ?> ), but it seems to work.

Now comes the fun part... integrating this into a much larger build. My head hurts and I haven't even started it. I'll give your guys a call if I can't get it figured out.

For anyone else interested in messing around with HTML Geolocation  here's what I built so far.

<?php header('Content-type: text/html; charset=utf-8'); ?>
<?php
  
  // load viewer library
  $libraryPath = 'cmsb/lib/viewer_functions.php';
  $dirsToCheck = array('/change/this/directory/','','../','../../','../../../');
  foreach ($dirsToCheck as $dir) { if (@include_once("$dir$libraryPath")) { break; }}
  if (!function_exists('getRecords')) { die("Couldn't load viewer library, check filepath in sourcecode."); }
  if (!@$GLOBALS['GEOCODER_PLUGIN'])         { die("You must activate the Geocoder plugin before you can access this page."); }

  // error checking
  if (!@$GLOBALS['GEOCODER_PLUGIN']) { die("You must activate the Geocoder plugin before you can access this page."); }

  // set default values (not required)
  if (!array_key_exists('fromAddress', $_REQUEST)) { $_REQUEST['fromAddress'] = '10001'; }      // this is the default address/postalcode if none entered

  // get geocoding data
  list($myLat, $myLng) = geocodeAddress( @$_REQUEST['fromAddress'] );
  $kmOrMiles           = 'miles'; // can be 'miles' or 'km'
  $geoOptions          = geocoder_getOptions($myLat, $myLng, @$_REQUEST['maxDistance'], $kmOrMiles);

  // get records
  list($addressRecords, $addressMetaData) = getRecords(array(
    'tableName'     => 'listings',
  ) + $geoOptions);  // geoOptions WILL NOT override the above options

  // error checking
  $errorsAndAlerts = '';
  if (@$_REQUEST['search']) {
    if     (!@$_REQUEST['fromAddress']) { $errorsAndAlerts .= "No address entered!<br/>\n"; }
    elseif (!$myLat || !$myLng)         { $errorsAndAlerts .= "We couldn't determine your location, please try again!<br/>\n"; }
  }


?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Proximity search with results sorted by distance</title>
<style type="text/css">
  body, td { font-family: arial; font-size: 14px; }
</style>
</head>
<body>

  <h1>Proximity search with results sorted by distance</h1>
  
  <?php
$lat=(isset($_GET['lat']))?$_GET['lat']:'';
$long=(isset($_GET['long']))?$_GET['long']:'';
    if ($lat && $long) {
        $gotGeo = $lat.','.$long;
    } else {
        $gotGeo = '';
    }
?>

  <?php if (@$errorsAndAlerts): ?>
    <div style="color: #C00; font-weight: bold; font-size: 12px; font-family: arial;">
      <?php echo $errorsAndAlerts; ?><br/>
    </div>
  <?php endif ?>

  Enter your address or postal code to see nearby results:<br/>

  <form method="post" action="">
    <input type="hidden" name="search" value="1" />
    
    
    <button onclick="getLocation()">Geo</button>
    <input type="text" name="fromAddress" id="getgeo" value="<?php echo (@$_REQUEST['fromAddress'] = $gotGeo); ?>" placeholder="&nbsp;&nbsp;Geo Location"/>

    <select name="maxDistance">
      <option value="">at any distance</option>
      <option value="50"        <?php selectedIf(50, @$_REQUEST['maxDistance']) ?> >within 50 miles</option>
      <option value="25"        <?php selectedIf( 25, @$_REQUEST['maxDistance']) ?> >within 25 miles</option>
      <option value="20"        <?php selectedIf( 20, @$_REQUEST['maxDistance']) ?> >within 20 miles</option>
      <option value="15"        <?php selectedIf( 15, @$_REQUEST['maxDistance']) ?> >within 15 miles</option>
      <option value="10"        <?php selectedIf( 10, @$_REQUEST['maxDistance']) ?> >within 10 miles</option>
      <option value="5"        <?php selectedIf( 5,  @$_REQUEST['maxDistance']) ?> >within 5 miles</option>
    </select>

    <input type="submit" value="Search" />
  </form>

  <?php if (@$_REQUEST['search'] && !$errorsAndAlerts): ?>
    <ul style="line-height: 1.5">
    <?php foreach ($addressRecords as $record): ?>
      <li>
        <a href="<?php echo $record['_link']; ?>">
            Property Name: <?php echo htmlencode($record['name']) ?><br/>
            Address: <?php echo htmlencode($record['street_number']) ?> <?php echo htmlencode($record['street_address']) ?><br/>
            <?php echo htmlencode($record['city']) ?>, <?php echo htmlencode($record['state']) ?> <?php echo htmlencode($record['zip']) ?><br/>
        </a>
        (<?php
          if (@$record['_distance']) { print number_format($record['_distance'], 1) . " $kmOrMiles away"; }
          else                       { print "unknown distance"; }
        ?>)<br /><br />
      </li>
    <?php endforeach ?>

    <?php if (!$addressRecords): ?>
      <li>No results found!</li>
    <?php endif ?>

    </ul>
  <?php endif ?>

<script type="text/javascript">
var x = document.getElementById("getgeo");
function getLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(redirectToPosition);
    } else {
        x.innerHTML = "Geolocation is not supported by this browser.";
    }
}
function redirectToPosition(position) {
    window.location='geo-to-prox.php?lat='+position.coords.latitude+'&long='+position.coords.longitude;
}
</script>

</body>
</html>

Zicky

Attachments:

geo-to-prox.php 5K