integrate geo location api in a php website

Discussion in 'PHP' started by Sachy123, May 15, 2013.

  1. #1
    I have a question on how to integrate the location data onto my php code. I am trying to make a website which will allow users to search a particular listing via a map.
    its just like a real estate searching website...
    do you know if I have to store data for country, city and nieghbourhood in my database?
    or will it come real time?
    E.G "a user wants search all the properties in mumbai."
    > my database contains data about the location and adress of the property in mumbai.
    E.g there are 4 properties in mumbai.
    So when the user searches for properties in mumbai, he will type mumbai in the search bar and google api will point to mumbai , and the map should also show all the properties in mumbai with pointers
    So for this scenario, how many tables do I have to create and which columns.. do I have to have all the location data?
    And I would like to know if someone has a code snippet or database
    Your help will be much appreciated.
    Kind Regards
    S
     
    Sachy123, May 15, 2013 IP
  2. scottlpool2003

    scottlpool2003 Well-Known Member

    Messages:
    1,708
    Likes Received:
    49
    Best Answers:
    9
    Trophy Points:
    150
    #2
    I've only just started playing with Google Maps, and I have so far managed to integrate it into search results using data from my database.

    The geographics I have stored for pretty much every town/region in the UK are eastings, northings, longitude, latitude, post code, country. The longitude and latitude is what you use to pull the map.

    I haven't played with pointers (markers) yet, but you can add those in, there's a section in the code below where you can add markers.

    Here is what I have so far:

    
     
    <!DOCTYPE html >
      <head>
        <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
        <meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
        <title>PHP/MySQL & Google Maps Example</title>
      <?php include "includes/db.php";
     
      $sth = $dbconn->prepare("
      SELECT    TOP 1 longitude, latitude, postcode
      FROM        uk_postcode_05
      WHERE    (town LIKE '%$_GET[id]%') OR
                            (region LIKE '%$_GET[id]%')
      ");
      $sth->execute();
      $data = $sth->fetchAll();
     
      foreach ($data as $row){
      echo "<strong>Postcode Area: </strong>".$row['postcode']."<br />";
      }
      ?>
     
        <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
        <script type="text/javascript">
        //<![CDATA[
     
        var customIcons = {
          restaurant: {
            icon: 'http://labs.google.com/ridefinder/images/mm_20_blue.png',
            shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
          },
          bar: {
            icon: 'http://labs.google.com/ridefinder/images/mm_20_red.png',
            shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
          }
        };
     
        function load() {
          var map = new google.maps.Map(document.getElementById("map"), {
            center: new google.maps.LatLng(<?php echo "".$row['latitude']."";?>, <?php echo "".$row['longitude']."";?>),
            zoom: 13,
            mapTypeId: 'roadmap'
          });
          var infoWindow = new google.maps.InfoWindow;
     
          // Change this depending on the name of your PHP file
          downloadUrl("phpsqlajax_genxml.php", function(data) {
            var xml = data.responseXML;
            var markers = xml.documentElement.getElementsByTagName("marker");
            for (var i = 0; i < markers.length; i++) {
              var name = markers[i].getAttribute("name");
              var address = markers[i].getAttribute("address");
              var type = markers[i].getAttribute("type");
              var point = new google.maps.LatLng(
                  parseFloat(markers[i].getAttribute("lat")),
                  parseFloat(markers[i].getAttribute("lng")));
              var html = "<b>" + name + "</b> <br/>" + address;
              var icon = customIcons[type] || {};
              var marker = new google.maps.Marker({
                map: map,
                position: point,
                icon: icon.icon,
                shadow: icon.shadow
              });
              bindInfoWindow(marker, map, infoWindow, html);
            }
          });
        }
     
        function bindInfoWindow(marker, map, infoWindow, html) {
          google.maps.event.addListener(marker, 'click', function() {
            infoWindow.setContent(html);
            infoWindow.open(map, marker);
          });
        }
     
        function downloadUrl(url, callback) {
          var request = window.ActiveXObject ?
              new ActiveXObject('Microsoft.XMLHTTP') :
              new XMLHttpRequest;
     
          request.onreadystatechange = function() {
            if (request.readyState == 4) {
              request.onreadystatechange = doNothing;
              callback(request, request.status);
            }
          };
     
          request.open('GET', url, true);
          request.send(null);
        }
     
        function doNothing() {}
     
        //]]>
     
      </script>
     
      </head>
     
      <body onload="load()">
        <div id="map" style="width: 500px; height: 300px"></div>
      </body>
     
    </html>
    
    PHP:
     
    scottlpool2003, May 15, 2013 IP
  3. Sachy123

    Sachy123 Greenhorn

    Messages:
    3
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    21
    #3
    Thanks!!
    So this means that in the database table I should only store "latitude" and "longitude"?
    I mean if a user enters an adress, the latitude and longitudes will be captured automatically?

    I am just curious if I really need a Master table having all the country, city, nieghbourhood level data.. OR I dont need it..

    Cheers
     
    Sachy123, May 15, 2013 IP
  4. scottlpool2003

    scottlpool2003 Well-Known Member

    Messages:
    1,708
    Likes Received:
    49
    Best Answers:
    9
    Trophy Points:
    150
    #4
    I think you should take a look at the Google Maps API documentation there's so many different things you can do with it.

    Using the above code, you don't need to have it all stored in the database, you could do it based on user input and instead of longitude/latitude you can get the map based on an address input.

    Look here:
    http://maps.google.com/maps/api/geo...eatre+Parkway,+Mountain+View,+CA&sensor=false

    Notice how the address is formatted, but when you go to the link there's all sorts of other data:


    So using the address you can get the longitude and latitude and pull the map based on that.
     
    scottlpool2003, May 15, 2013 IP
  5. ThePHPMaster

    ThePHPMaster Well-Known Member

    Messages:
    737
    Likes Received:
    52
    Best Answers:
    33
    Trophy Points:
    150
    #5
    It sounds to me like you are trying to do the same functionality as a "store locator". Instead of store, you replace it with properties.

    The best way to do this is to use the closest latitude/longitude option. It is almost pretty much coded for you by Google (with option to search within x miles from city as well):

    https://developers.google.com/maps/articles/phpsqlsearch_v3
     
    ThePHPMaster, May 15, 2013 IP
  6. nico_swd

    nico_swd Prominent Member

    Messages:
    4,153
    Likes Received:
    344
    Best Answers:
    18
    Trophy Points:
    375
    #6

    By putting the raw $_GET data into the query string, you're defeating the purpose of prepared statements. This is just as vulnerable to SQL injections as any unescaped data in a mysql_query() statement.

    Do this instead:
    
     
      $sth = $dbconn->prepare("
      SELECT    TOP 1 longitude, latitude, postcode
      FROM        uk_postcode_05
      WHERE    (town LIKE ?) OR
                            (region LIKE ?)
      ");
      $id = '%' . $_GET['id'] . '%';
      $sth->execute([$id, $id]);
      $data = $sth->fetchAll();
    
    PHP:
     
    nico_swd, May 15, 2013 IP
  7. scottlpool2003

    scottlpool2003 Well-Known Member

    Messages:
    1,708
    Likes Received:
    49
    Best Answers:
    9
    Trophy Points:
    150
    #7

    Whoops, that's my demo code. You should never directly put the variables whether $_GET or $_POST or even $var in the PDO query as it defeats the object of doing it in the first place.

    My code was just something I was playing around with, the above is much more secure.
     
    scottlpool2003, May 16, 2013 IP
  8. cochisetm

    cochisetm Member

    Messages:
    80
    Likes Received:
    5
    Best Answers:
    0
    Trophy Points:
    33
    #8
    It does sound like this is more of a store locator request that then simply plots the close points on a map? If so, and you can do a lot with storing the long/lat of your properties and then making simple Google Map API calls to plot those points. You can use Google's API to get the long/lat of any properly formatted address. I would start by storing those as having the long/lat locally will provide a lot of future flexibility.
     
    cochisetm, Jun 6, 2013 IP