jfive
jfive

Reputation: 56

Returning javascript results for use in php

I have a database that stores clients and employees. The front end for that database uses very old software (coded in vb6 from the late 90s so I can't simply geocode the addresses for insertion upon entry, unless i wanna do some fancy sql work). I am building some more robust reporting software for the data. I want to include google map features in the software that shows where clients and employees live. When a roster of current employees or clients is generated, I also want it to check for new additions and then geocode their addresses into a database table so that I can reference them in later reports. I have no problem with recognizing the new entries or geocoding their locations.

The way the php script works is it checks to see if clients have latitude and longitude information populated already, and if not, get the lat/lng, and then insert it into the database. If there are several new clients/employees, i want it to loop through the result set and insert the relative information. The issue is the google api gets the lat/lng via javascript, so I can't pass that information back into the php script to store it into the database, and I don't really want to use javascript to insert it.

So i'm wondering the best way to go about this. I have been researching and testing for a couple hours now. I figured I could probably pass the variables through ajax techniques, but isn't that going to cause an issue when doing it in the middle of a loop?

Here's some sample code, and I apologize for such a drawn out question!

Javascript snippet of geocode:

function codeAddress(address) {

  geocoder.geocode( { 'address': address}, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
        var newlat = results[0].geometry.location.lat();
        var newlng = results[0].geometry.location.lng();
        alert(results[0].geometry.location);


    } else {
      alert('Geocode was not successful for the following reason: ' + status);
    }
  });

php snippet:

$address = "";
$num = 0;
//Google geocode limits requests to 10 per second, limit to 5 total requests at a time.
//If more theres more than 10 clients who have yet to be geocoded, running the database insertion code
//---should provide long enough delay to geocode again and not hit the overflow limit


while ($row = mssql_fetch_array($result) and $num < 5) {
   if ($row['lat'] == "") {
        //Create address string
        $address = $row['Address1'] . " " . $row['City'] . ", NY " . $row['Zip'];
        $address = str_replace("'", "", $address);
       //Test to show addresses without lat/lng were pulled
        echo "<script>codeAddress('" . $address . "');</script>" . $address . "<br />";
        $num = $num + 1;
        }

    }

Upvotes: 0

Views: 137

Answers (1)

AniV
AniV

Reputation: 4037

Here is the code to convert address into geocoordinates (lat, lang):

<?php
      $Address = urlencode($Address);
      $request_url = "http://maps.googleapis.com/maps/api/geocode/xml?address=".$Address."&sensor=true";
      $xml = simplexml_load_file($request_url) or die("url not loading");
      $status = $xml->status;
      if ($status=="OK") {
          $Lat = $xml->result->geometry->location->lat;
          $Lon = $xml->result->geometry->location->lng;
          $LatLng = "$Lat,$Lon";
      }
    ?>

You can store these Lat Lng in Database with a simple SQL query and then retrieve it back to display on the map. For that you have to display the Map. See the following code to doo that:

<!DOCTYPE html>

<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>Google Maps Example</title>
        <style type="text/css">
            body { font: normal 14px Verdana; }
            h1 { font-size: 24px; }
            h2 { font-size: 18px; }
            #sidebar { float: right; width: 30%; }
            #main { padding-right: 15px; }
            .infoWindow { width: 220px; }
        </style>
        <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
        <script type="text/javascript">
        //<![CDATA[

        var map;

        // Ban Jelačić Square - Center of Zagreb, Croatia
        var center = new google.maps.LatLng(45.812897, 15.97706);

        function init() {

            var mapOptions = {
                zoom: 13,
                center: center,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            }

            map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);

            var marker = new google.maps.Marker({
                map: map, 
                position: center,
            });
        }
        //]]>
        </script>
    </head>
    <body onload="init();">

        <h1>Places to check out in Zagreb</h1>

        <section id="sidebar">
            <div id="directions_panel"></div>
        </section>

        <section id="main">
            <div id="map_canvas" style="width: 70%; height: 500px;"></div>
        </section>

    </body>
</html>

To get the data from the Database:

<?php

$server     = 'localhost';
$username   = 'root';
$password   = 'YOUR_PASSWORD';
$database   = 'YOUR_DATABASE';

$dsn        = "mysql:host=$server;dbname=$database";

Now Create your own file that will return the actual data.

<?php

    require 'config.php';

    try {

        $db = new PDO($dsn, $username, $password);
        $db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );

        $sth = $db->query("SELECT * FROM locations");
        $locations = $sth->fetchAll();

        echo json_encode( $locations );

    } catch (Exception $e) {
        echo $e->getMessage();
    }

To display locations on the map you have to make AJAX requests:

function makeRequest(url, callback) {
    var request;
    if (window.XMLHttpRequest) {
        request = new XMLHttpRequest(); // IE7+, Firefox, Chrome, Opera, Safari
    } else {
        request = new ActiveXObject("Microsoft.XMLHTTP"); // IE6, IE5
    }
    request.onreadystatechange = function() {
        if (request.readyState == 4 && request.status == 200) {
            callback(request);
        }
    }
    request.open("GET", url, true);
    request.send();
}

Define your init() function which will have the JSON response:

var map;

// Ban Jelačić Square - City Center
var center = new google.maps.LatLng(45.812897, 15.97706);

var geocoder = new google.maps.Geocoder();
var infowindow = new google.maps.InfoWindow();

function init() {

    var mapOptions = {
      zoom: 13,
      center: center,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    }

    map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);

    makeRequest('get_locations.php', function(data) {

        var data = JSON.parse(data.responseText);

        for (var i = 0; i < data.length; i++) {
            displayLocation(data[i]);
        }
    });
}

Finally you need to display the locations on the map, you can add a info window like this:

function displayLocation(location) {

    var content =   '<div class="infoWindow"><strong>'  + location.name + '</strong>'
                    + '<br/>'     + location.address
                    + '<br/>'     + location.description + '</div>';

    if (parseInt(location.lat) == 0) {
        geocoder.geocode( { 'address': location.address }, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {

                var marker = new google.maps.Marker({
                    map: map, 
                    position: results[0].geometry.location,
                    title: location.name
                });

                google.maps.event.addListener(marker, 'click', function() {
                    infowindow.setContent(content);
                    infowindow.open(map,marker);
                });
            }
        });
    } else {
        var position = new google.maps.LatLng(parseFloat(location.lat), parseFloat(location.lon));
        var marker = new google.maps.Marker({
            map: map, 
            position: position,
            title: location.name
        });

        google.maps.event.addListener(marker, 'click', function() {
            infowindow.setContent(content);
            infowindow.open(map,marker);
        });
    }
}

Hope this Helps!!

Upvotes: 1

Related Questions