Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 6 of 6
  1. #1
    Master Coder
    Join Date
    Jun 2003
    Location
    Cottage Grove, Minnesota
    Posts
    9,500
    Thanks
    8
    Thanked 1,089 Times in 1,080 Posts

    Using Google Map V3 - Example of GPS Marking

    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 Code:
    <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 Code:
    <?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.
    "
    ;

    ?>

    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 http://www.geocaching.com

    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.


    Have fun!




    .

  2. The Following 2 Users Say Thank You to mlseim For This Useful Post:

    djm0219 (02-03-2011), oesxyl (02-03-2011)

  • #2
    Master Coder
    Join Date
    Jun 2003
    Location
    Cottage Grove, Minnesota
    Posts
    9,500
    Thanks
    8
    Thanked 1,089 Times in 1,080 Posts
    NOTE:

    There is a newer version ... you can see when you go to the test site:
    http://www.catpin.com/gps

    The new option to "center the map" on the marker.
    And with cookies, it will remember that spot on your PC.

    Here is the new script:
    PHP Code:
    <?php

    // get the new map center if user requested it.
    $latlon="44.955440188735956, -93.10223236419678";
    if (isset(
    $_COOKIE['center'])){
    $latlon=$_COOKIE['center'];
    }
    // get the new map zoom if user requested it.
    $startzoom=16;
    if (isset(
    $_COOKIE['zoom'])){
    $startzoom=$_COOKIE['zoom'];
    }
    ?>
    <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(', ');
      
      latDir = "N";
      lngDir = "E";
      if(latLng.lat() < 0){
      latDir = "S";
      }
      if(latLng.lng() < 0){
      lngDir = "W";
      }
      qlat = Math.abs(latLng.lat());
      ilat = Math.floor(qlat);
      xlat = ((qlat - ilat)*60);
      
      qlng = Math.abs(latLng.lng());
      ilng = Math.floor(qlng);
      xlng = ((qlng - ilng)*60);
      
      xlat = Math.round(xlat*1000)/1000;
      xlng = Math.round(xlng*1000)/1000; 

    d2 = xlat.toFixed(3);
    e2 = xlng.toFixed(3);   
    d1 = ilat.toString();
    d2 = d2.toString();
    e1 = ilng.toString();
    e2 = e2.toString();
      
      n = Math.abs(latLng.lat()); // Change to positive var decimal = n - Math.floor(n)
      var decimal = n - Math.floor(n); 
      document.getElementById('geot').innerHTML = [
        latDir + ' ' + d1 + ' ' + d2,
        lngDir + ' ' + e1 + ' ' + e2
      ].join(', ');
      
      document.form1.lat.value = [
        latLng.lat()];
      document.form1.lon.value = [
        latLng.lng()];
      document.form1.wlat.value = [
        latDir + ' ' + d1 + ' ' + d2];
      document.form1.wlon.value = [
        lngDir + ' ' + e1 + ' ' + e2];
    }

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

    function centerPosition(newgeo,newzoom) {
    // document.getElementById('mcenter').innerHTML = [newgeo];
    // document.getElementById('mzoom').innerHTML = [newzoom];
    document.form2.mcenter2.value = [newgeo];
    document.form2.mzoom2.value = [newzoom];
    document.form1.zm2.value = [newzoom];
    }

    function initialize() {
      var latLng = new google.maps.LatLng(<?=$latlon?>);
      var map = new google.maps.Map(document.getElementById('mapCanvas'), {
        zoom: <?=$startzoom?>,
        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());
      });
      
      google.maps.event.addListener(map, 'bounds_changed', function(){
        var newgeo = map.get('center');
         var newzoom = map.get('zoom');
        centerPosition(newgeo,newzoom);
      });
           
    }

    // Onload handler to fire off the app.
    google.maps.event.addDomListener(window, 'load', initialize);
    </script>
    </head>
      <style>
      body{
      font-family: arial;
      font-size: 13px;
      width:1300px;
      }
      #container{
      width:1300px;
      }
      #mapCanvas {
        width: 600px;
        height: 500px;
        float: left;
      }
      #infoPanel {
      width: 600px;
        float: left;
        margin-left: 10px;
      }
      #infoPanel div {
        margin-bottom: 5px;
      }
       </style>
    <body>
     <div id="container">
      <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 (by decimal):</b>
        <div id="info"></div>
        <b>WGS-84 GeoTracker (by minutes):</b>
        <div id="geot"></div>
        <b>Closest matching address:</b>
        <div id="address"></div>

        
        <form id="form1" name="form1" action="add.php" method="post">
        <input type="hidden" name="zm" id="zm2" value="zm2">
        <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 />
        <b>WGS-84 Lat</b> <input type="text" id="wlat" name="wlat" size="10"><br />
        <b>WGS-84 Lon</b> <input type="text" id="wlon" name="wlon" size="10"><br />
        <input type="submit" name="submit" value="Get Google Map Code">
        </form>
        <br /><br />
        <!--
        <b>Current map center:</b>
        <div id="mcenter"></div>
        <div style="float:left;"><b>Current map zoom level: &nbsp;</b></div><div id="mzoom" style="float:left;"></div>
        <div style="clear:both;"></div>
        -->
        <form id="form2" name="form2" method="post" action="center.php">
        <input type="hidden" name="newcenter" id="mcenter2" value="mcenter2">
        <input type="hidden" name="newzoom" id="mzoom2" value="mzoom2">
        <input type="submit" name="submit" value="Center Marker On Map">
        </form>
        <div style="width:300px; font-size:10pt; color:#999; text-align:justify;">'Center Marker On Map' will remember where the center of this map is, and also the zoom level ... using cookies.  The next time you access this page, your settings will be remembered on this computer.</div>
        </div>
      </div>
    </body>
    </html>

    And here is the script called "center.php":
    PHP Code:
    <?php
    $center
    =$_POST['newcenter'];
    $zoom=$_POST['newzoom'];
    $center=str_replace("(","",$center);
    $center=str_replace(")","",$center);
    setcookie("center"$centertime()+604800);
    setcookie("zoom"$zoomtime()+604800);
    header ("location: index.php");
    ?>

    Here is the script called "add.php":
    PHP Code:
    <?php

    $lat
    =$_POST['lat'];
    $lon=$_POST['lon'];
    $zm=$_POST['zm'];
    $wlat $_POST['wlat'];
    $wlon $_POST['wlon'];

    // save location in a cookie
    $center=$wlat.",".$wlon;
    setcookie("center"$centertime()+604800);
    setcookie("zoom"$zmtime()+604800);

    echo 
    "<br /><br />Email this link to whoever needs to see your location:<br /><br />
    http://maps.google.com/maps?q=$lat,+$lon&iwloc=A&hl=en&z=$zm
    "
    ;

    ?>

    .

  • #3
    New to the CF scene
    Join Date
    Jan 2012
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Hi,
    Your code look great!!!!
    may I know how can set the marker to center without refresh?
    As, I would like to do a registration page with have other textbox and I would be help if dun need to reflesh the page.

    Thanks a lot.!!!

  • #4
    12k
    12k is offline
    New Coder
    Join Date
    Jan 2012
    Posts
    29
    Thanks
    0
    Thanked 6 Times in 6 Posts
    Very nice work. I havent got to work with this yet. Just when I was about to I had got a different project. Looks very interesting. I might just start toying with it xD

  • #5
    New to the CF scene
    Join Date
    Jan 2012
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Search for current location automatic?

    My name is Sebastian and for a school project could somebody help me with some minor adjustment within this code?

    I'm searching for a feature where the marker searches for your current location automatic and only require the "Closest matching address:" to the displayed beneath the map in a "textfield" just like the Longitude and Latitude are now presented.

    Any help would be very appreciated
    Last edited by sebastian_01; 01-23-2012 at 10:56 PM.

  • #6
    New to the CF scene
    Join Date
    Mar 2012
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Hi mlseim,

    I have quite similar problems. Basically I save a user's location selection and will set it as a default when opening the map again. That works fine. But I would also like to give users an option to directly select another location based on an address to avoid them being 'stuck' at the default location and having to spend a minute to click themselves through to another spot on the other side of the globe… ;-)

    So I added a text field

    Code:
    <form>
    	<input type="text" id="addressInput" size="40" />
        <input type="button" onclick="searchLocations()" value="&nbsp;Go!&nbsp;"/>
    	</form>
    and added the following Javascript code to refresh the map based on the location:

    Code:
    function searchLocations() {
    var address = document.getElementById('addressInput').value;
    var geocoder3 = new google.maps.Geocoder();
    geocoder3.geocode({ 'address': address }, function (results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
    	map.setCenter(results[0].geometry.location,15);
    }else{
    	alert(address + ' could not be geocoded (=not found) .. \nPlease enter an address in the format STREET NAME, CITY');
    }
    });	
    }
    I can see the map refreshing after clicking the submit button, but it is keeping the same location although I tested that the function is indeed called (it is also giving the error message if an address cannot be reverse geocoded). So there seems to be something wrong with refreshing the map in my code.

    kind regards,
    r.
    Last edited by rookey; 03-27-2012 at 09:28 AM.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •