Welcome to WebDesignForums.net!
You're currently viewing WDF as a guest. By registering for a free account, you'll be able to participate with other members in our friendly community. Being a member allows you to ask questions and get answers for those troublesome web development tasks!

In addition, as a member you'll be able to post your websites up for review. Using our unique website review system you can gain some amazing feedback from some of the best web developers around. This is a completely free service to all registered members.

Ready to register yet? Registration is 100% free. Click Here To Join Now!

Using Google Maps V3 - Working Example

Discussion in 'General Web Design Discussion' started by mlseim, Feb 3, 2011.

  1. Offline

    mlseim WDF Staff

    Message Count:
    5,484
    Likes Received:
    224
    Trophy Points:
    63
    Gender:
    Male
    Location:
    Cottage Grove, Minnesota
    I get asked periodically for examples on how to find GPS coordinates
    for Google Map projects, picking locations on a map and saving them
    into a database, etc.

    So, below is a working example of how to use the free Google Maps API V3,
    along with PHP to emulate getting GPS coordinates for a database.

    You could use this for simply finding the exact GPS location anywhere.
    Zooming in will focus the GPS on a very accurate spot on the earth.

    Google no longer requires any API keys, so you can copy and paste both
    scripts into your website and play around. The key part to set-up is the
    initial GPS location (when it loads) and the zoom level. For my example,
    it loads on the Minnesota Capitol with a zoom of 16. It also loads in
    "map" view, but you could also initialize in "hybrid" or "satellite".

    Here is my working example:
    http://www.catpin.com/gps

    Drag the marker around, switch Map views ... use it to find
    exact GPS coordinates.

    Here is the complete script you can copy and paste yourself.
    Then upload to your own website.
    PHP:

    <html>
    <
    head>
    <
    meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
    <
    script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
    <script type="text/javascript">
    var geocoder = new google.maps.Geocoder();

    function geocodePosition(pos) {
      geocoder.geocode({
        latLng: pos
      }, function(responses) {
        if (responses && responses.length > 0) {
          updateMarkerAddress(responses[0].formatted_address);
        } else {
          updateMarkerAddress('Cannot determine address at this location.');
        }
      });
    }

    function updateMarkerStatus(str) {
      document.getElementById('markerStatus').innerHTML = str;
    }

    function updateMarkerPosition(latLng) {
      document.getElementById('info').innerHTML = [
        latLng.lat(),
        latLng.lng()
      ].join(', ');
      //document.getElementById('posit').innerHTML = [
      document.form1.lat.value = [
        latLng.lat()];
      document.form1.lon.value = [
        latLng.lng()];
    }

    function updateMarkerAddress(str) {
      document.getElementById('address').innerHTML = str;
    }

    function initialize() {
      var latLng = new google.maps.LatLng(44.955440188735956, -93.10223236419678);
      var map = new google.maps.Map(document.getElementById('mapCanvas'), {
        zoom: 16,
        center: latLng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
      });
      var marker = new google.maps.Marker({
        position: latLng,
        title: 'Point A',
        map: map,
        draggable: true
      });
      
      // Update current position info.
      updateMarkerPosition(latLng);
      geocodePosition(latLng);
      
      // Add dragging event listeners.
      google.maps.event.addListener(marker, 'dragstart', function() {
        updateMarkerAddress('Dragging...');
      });
      
      google.maps.event.addListener(marker, 'drag', function() {
        updateMarkerStatus('Dragging...');
        updateMarkerPosition(marker.getPosition());
      });
      
      google.maps.event.addListener(marker, 'dragend', function() {
        updateMarkerStatus('Drag ended');
        geocodePosition(marker.getPosition());
      });
    }

    // Onload handler to fire off the app.
    google.maps.event.addDomListener(window, 'load', initialize);
    </script>
    </head>
    <body>
      <style>
      body{
      font-family: arial;
      font-size: 13px;
      }
      #mapCanvas {
        width: 600px;
        height: 500px;
        float: left;
      }
      #infoPanel {
        float: left;
        margin-left: 10px;
      }
      #infoPanel div {
        margin-bottom: 5px;
      }
       </style>
      
      <div id="mapCanvas"></div>
      <div id="infoPanel">
        <b>Marker status:</b>

        <div id="markerStatus"><i>Click and drag the marker.</i></div>
        <b>Current position:</b>
        <div id="info"></div>
        <b>Closest matching address:</b>
        <div id="address"></div>
        
        <form id="form1" name="form1" action="add.php" method="post">
        <b>&nbsp; Latitude:</b> <input type="text" id="lat" name="lat" size="18"> <br />
        <b>Longitude:</b> <input type="text" id="lon" name="lon" size="18"> <br />
        <input type="submit" name="submit" value="Add Point">
        </form>
      </div>
    </body>
    </html>


    This is the PHP script called "add.php" ... that will process the GPS:
    PHP:

    <?php

    $lat
    =$_POST['lat'];
    $lon=$_POST['lon'];

    echo
    "
    This is the PHP script to process your GPS location:<br ?><br />
    Latitude: 
    $lat<br />
    Longitude: 
    $lon<br />
    <br />
    <br />
    At this point, you would be adding it to a database, or asking<br />
    for more information, comments, etc.
    "
    ;

    ?>
    Have fun!




    .


  2. Offline

    Dorky Freelance

    Message Count:
    1,424
    Likes Received:
    4
    Trophy Points:
    0
    Location:
    Destin Florida
    can you elaborate on some uses of this. i found it pretty cool but i didn't understand the long and lat inputs or what i was supposed to do with them.


  3. Offline

    mlseim WDF Staff

    Message Count:
    5,484
    Likes Received:
    224
    Trophy Points:
    63
    Gender:
    Male
    Location:
    Cottage Grove, Minnesota
    A few ideas ....

    1) You might want to create a map of where clients or businesses are located
    within a city (who is closest to me?). You have your clients move the marker
    to their business and click. It saves their GPS coordinate in a database for you to
    use on a map (the closest business to me?) for your site visitors.

    2) You can create locations for Geocaching (where people look for physical caches).
    see Geocaching - The Official Global GPS Cache Hunt Site

    3) Someone doing a family geneology project could use it to mark gravesite locations
    for the GEDCOM database. Those GPS locations can be displayed on any other maps
    that people would use to find family information.

    4) A "meet me here" mobile phone app for physical social networking.

    5) A "this is where I'm at now" mobile phone app for letting someone else know
    where you're at. Or, the party is here.


    The application I'm showing is the part where someone "marks" the location.
    Once marked and stored in a database, any other web page or application can
    use those markers on other Google Maps ... or ANY other mapping (like Bing),
    because of the actual GPS coordinates.

    The GPS coordinates are a physical location on the Earth. If you post the
    GPS coordinates of where your house is at, anyone could punch them into
    an online map (Google or anyone else), and pinpoint the location on a map.




    .


  4. Offline

    Seenu Reddi New Member

    Message Count:
    3
    Likes Received:
    0
    Trophy Points:
    1
    Gender:
    Male
    Location:
    Irvine, California
    It is probably discouraging to receive negative responses after a lot of hard work especially from people that do not understand what it is about. I think your app is great because it cuts a lot of bullshoot and gets to the point of getting the coordinates from google maps. I have been struggling with the copious amounts of information about google maps with no clue whatsoever how to extract information them. Thank you for your great app and contribution.


  5. Offline

    mlseim WDF Staff

    Message Count:
    5,484
    Likes Received:
    224
    Trophy Points:
    63
    Gender:
    Male
    Location:
    Cottage Grove, Minnesota
    Seenu,
    Thanks.
    My programming ego doesn't get bruised too easily ... I don't take it quite that seriously.
    It's important to keep having fun doing it, and I learn much more by the comments,
    whether they are criticism, advice, or someone correcting my errors.

    And I keep stumbling across stuff that has been around a while, but I never knew it.
    The latest thing I discovered was Yahoo's feature ... where you only need to ask for
    a user's zipcode to get their city, state, and geo-location. Been around forever, but
    I never knew that.

    Like this ... for your location .... Irvine, California ...
    http://local.yahooapis.com/MapsService/V1/geocode?appid=1&zip=92620

    The result is XML ... where a PHP script can then extract all necessary information.

    Instead of asking someone for their city, state, and zipcode ... I only ask for the zipcode.

    .


  6. Offline

    Seenu Reddi New Member

    Message Count:
    3
    Likes Received:
    0
    Trophy Points:
    1
    Gender:
    Male
    Location:
    Irvine, California


  7. Offline

    Seenu Reddi New Member

    Message Count:
    3
    Likes Received:
    0
    Trophy Points:
    1
    Gender:
    Male
    Location:
    Irvine, California
    That's interesting and I can certainly use it in my application for facebook which I am still developing (http://apps.facebook.com/sastraus) but I need time zones also. In principle I should be able to deduce from the coordinates but it would be nice if I get this information. http://www.boutell.com/zipcodes/ has a database that contains zip codes, coordinates and the time zones. Also my app needs to be international - your app gives the coordinates from the map. The book Map Scripting 101 gives similar examples of geocoding using Mapstraction as a common framework for Yahoo and Google but I cannot find the source code for the examples given in the book.


  8. Offline

    mlseim WDF Staff

    Message Count:
    5,484
    Likes Received:
    224
    Trophy Points:
    63
    Gender:
    Male
    Location:
    Cottage Grove, Minnesota
    The timezone thing will be a bit harder to do ... I'll have to study it more.

    You have countries that don't observe DST and some countries have chosen
    to be 15 minutes different than others. In the U.S., you have Arizona that
    does not observer DST, yet a tiny area of Arizona does (indian reservation).

    The DST system is a total mess.

    The closest thing I was able to do ... was to have the user pick a key city that
    is within their same timezone. PHP has a "specific list" that determines timezones.
    My example can be found in the right-hand column of this site ...
    http://www.starpointradio.com

    The "Timezoner" lets the user pick their timezone so that the show schedule
    reflects the user's time, not the station's time (in England). My problem is that
    not all user's know which city to pick. But it's the best I've been able to do so far.

    .


  9. Offline

    PedroNGV New Member

    Message Count:
    3
    Likes Received:
    0
    Trophy Points:
    1
    Gender:
    Male
    Hello mlseim

    This application is great! It was just what I was looking for :) and it was during this search that I found the forum!

    In my case, I'm interested that, initially, the latitude and longitude fields appear blank and that they are filled only after the user move the marker. Is it possible?

    This is because, in a form where the user does not move the marker, are always submitted the initial coordinates.

    Sorry to be only asking and not putting it forward with a solution, but I am now taking the first steps in PHP and JavaScript programming, so far I only worked with HTML.

    Thank you very much!


  10. Offline

    mlseim WDF Staff

    Message Count:
    5,484
    Likes Received:
    224
    Trophy Points:
    63
    Gender:
    Male
    Location:
    Cottage Grove, Minnesota
    Pedro ...

    See this version:
    http://www.catpin.com/gps/index2.php

    It's the same thing, but I don't show the initial coordinates.
    The coordinates only appear when the marker is moved.

    If someone submits without moving the marker, your PHP script
    will easily see that the lat and lon values are null (or blank).

    Look at the HTML source code of the "index2.php" file using
    your browser (click View, mouse down to HTML Source ... or Source).
    All I did was "comment-out" one line in the Javascripting.

    .


    PedroNGV likes this.
  11. Offline

    PedroNGV New Member

    Message Count:
    3
    Likes Received:
    0
    Trophy Points:
    1
    Gender:
    Male
    Hello mlseim

    Thank you very much!

    After all it was a simple thing! :) This way is much better, so it ensures that the user moves the marker.

    Excellent! Thank you for sharing this application! It helps a lot!

    Just as a suggestion, another interesting possibility would be to place the cursor with only a mouse click instead of dragging the marker.

    Best regards!


  12. Offline

    mlseim WDF Staff

    Message Count:
    5,484
    Likes Received:
    224
    Trophy Points:
    63
    Gender:
    Male
    Location:
    Cottage Grove, Minnesota
    Pedro ...
    There is a slight problem with that idea ...
    The marker "X" is not exactly at the base of the marker.
    This would be hard for a user to place it without dragging.


    .


  13. Offline

    PedroNGV New Member

    Message Count:
    3
    Likes Received:
    0
    Trophy Points:
    1
    Gender:
    Male
    Oh ok mlseim, thanks for the clarification!

    I also thought another big problem with this idea ... It would be impossible to use the street view and move the map also become painful.

    All in all, this form of drag the marker is undoubtedly the best option!

    Once again, thanks for sharing mlseim!!

    Best regards!


  14. Offline

    nancyparrishnrs New Member

    Message Count:
    1
    Likes Received:
    0
    Trophy Points:
    1
    I think your app is great because it cuts a lot of bullshoot and gets to the point of getting the coordinates from google maps.
    ------
    Nancy
    Payroll Solutions


  15. Offline

    Stefan Schneider New Member

    Message Count:
    4
    Likes Received:
    0
    Trophy Points:
    1
    Gender:
    Male
    Location:
    Taipei, Taiwan


  16. Offline

    mlseim WDF Staff

    Message Count:
    5,484
    Likes Received:
    224
    Trophy Points:
    63
    Gender:
    Male
    Location:
    Cottage Grove, Minnesota
    You'll have to elaborate some more.
    What your script should do, what the "failure" is, and a link or URL to your actual script.


    .


  17. Offline

    Stefan Schneider New Member

    Message Count:
    4
    Likes Received:
    0
    Trophy Points:
    1
    Gender:
    Male
    Location:
    Taipei, Taiwan
    Hi mlseim,

    here is the link: http://www.twdeal.com/example/showcase.html
    Exactly your script just displayed a little different. Input fields and lat/lng are saved in a mysql database.

    What I am looking for is: One map that accomplishes several things
    1. Picks the coordinates of a marker and saves them in a database. Your script does exactly that. I use your script as a a basis and want to build on it.
    2. Show all the database entries with a radius of say 3 miles around the center of the map. I.e. it should not load all existing database entries but only those which are around a radius of 3 miles where the map is centered.
    3. The map should use the users geolocation when loaded and have a button "My Location" to always go back to my geolocation.
    I will pay for that, just let me know, send me a mail to schneiderstefan1@gmail.com

    Thanks!


  18. Offline

    mlseim WDF Staff

    Message Count:
    5,484
    Likes Received:
    224
    Trophy Points:
    63
    Gender:
    Male
    Location:
    Cottage Grove, Minnesota
    How are you displaying all markers once you have them in a database?
    Do you have any examples of that?

    I would like to see your script where you display all markers,
    and then I might be able to add the circle (radius) in the center.
    We can deal with only showing the markers in the circle later on.

    .


  19. Offline

    Stefan Schneider New Member

    Message Count:
    4
    Likes Received:
    0
    Trophy Points:
    1
    Gender:
    Male
    Location:
    Taipei, Taiwan


  20. Offline

    mlseim WDF Staff

    Message Count:
    5,484
    Likes Received:
    224
    Trophy Points:
    63
    Gender:
    Male
    Location:
    Cottage Grove, Minnesota
    How do you know what the user's location is?
    Do you have them log-in?

    Here's an example of a 1KM radius circle that goes around
    the clicked marker, and the marker gets centered when clicked,
    and also pops up a text box. These markers are read from an
    XML file. In your case, I think you want the circle around the
    user's location? Once again, do you have any sort of code for
    showing your markers?

    Here's the example:
    http://www.meseim.com/geo/index3.php

    Is that anything similar to what you're looking for?

    .


Share This Page