www.webdeveloper.com
Page 1 of 2 12 LastLast
Results 1 to 15 of 16

Thread: java script geo tracking website users for directions

  1. #1
    Join Date
    Aug 2012
    Location
    TX
    Posts
    293

    java script geo tracking website users for directions

    I have a google map on my site. and i have a form that auto fills the persons lat and long when they fill it out.

    what i want to do is make the map on my main page show my office as a waypoint which it does... and then get there lat and lang to provide them with directions to my office.


    I would provide code but i have recoded this 100 times today have ten hours in to it and still can not get it to work... will someone please write a script for me and explain it line by line so I
    can understand where I have been going wrong?

  2. #2
    Join Date
    Nov 2010
    Posts
    1,049
    wouldn't that basically be this:
    https://google-developers.appspot.co...rections-panel

    with a text input for the start and the end hardcoded?

  3. #3
    Join Date
    Aug 2012
    Location
    TX
    Posts
    293
    i was planing on setting a waypoint to the office. so it can not be changed. then who ever is using the website url accepts us using their location so we can immediately give them directions straight to the shop from out home page. employees work in the field and carry tablets and laptops... it would be nice to have everything centralized on one site which is what i have been doing.

    i want the url to grab the lat and long from the user and automatically set their directions up to the office in the map in the footer.

    www.ogsolutions.us/aziz

  4. #4
    Join Date
    Aug 2012
    Location
    TX
    Posts
    293
    see what you sent me would work... I could embed that in the iframe but what if the user is driving down the road. I need them to have directions auoto populate based on their geo location

  5. #5
    Join Date
    Nov 2010
    Posts
    1,049
    so set the start position using geolocation:
    https://google-developers.appspot.co...ap-geolocation

    But I would recommend building in some error handling in case:
    a) geolocation fails
    b) the user refuses to share their location
    c) the geolocator gets confused (between, say paris, france and paris, texas)
    d) geolocation succeeds, but is a few km off (which is not at all rare - I have seen it return results that were several hundred kilometers off target)

  6. #6
    Join Date
    Aug 2012
    Location
    TX
    Posts
    293
    This is what i have... but i need the forms to auto populate with the correct coords amd I would like the map to be viewing


    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8" />
    <title>Find a route using Geolocation and Google Maps API</title>
    <script src="http://maps.google.com/maps/api/js?sensor=true"></script>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script>
    function calculateRoute(from, to) {
    // Center initialized to Naples, Italy
    var myOptions = {
    zoom: 10,
    center: new google.maps.LatLng(32.794213,-96.618572);
    mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    // Draw the map
    var mapObject = new google.maps.Map(document.getElementById("map"), myOptions);
    var directionsService = new google.maps.DirectionsService();
    var directionsRequest = {
    origin: from,
    destination: to,
    travelMode: google.maps.DirectionsTravelMode.DRIVING,
    unitSystem: google.maps.UnitSystem.METRIC
    };
    directionsService.route(
    directionsRequest,
    function(response, status)
    {
    if (status == google.maps.DirectionsStatus.OK)
    {
    new google.maps.DirectionsRenderer({
    map: mapObject,
    directions: response
    });
    }
    else
    $("#error").append("Unable to retrieve your route<br />");
    }
    );
    }
    $(document).ready(function() {
    // If the browser supports the Geolocation API
    if (typeof navigator.geolocation == "undefined") {
    $("#error").text("Your browser doesn't support the Geolocation API");
    return;
    }
    $("#from-link, #to-link").click(function(event) {
    event.preventDefault();
    var addressId = this.id.substring(0, this.id.indexOf("-"));
    navigator.geolocation.getCurrentPosition(function(position) {
    var geocoder = new google.maps.Geocoder();
    geocoder.geocode({
    "location": new google.maps.LatLng(position.coords.latitude, position.coords.longitude)
    },
    function(results, status) {
    if (status == google.maps.GeocoderStatus.OK)
    $("#" + addressId).val(results[0].formatted_address);
    else
    $("#error").append("Unable to retrieve your address<br />");
    });
    },
    function(positionError){
    $("#error").append("Error: " + positionError.message + "<br />");
    },
    {
    enableHighAccuracy: true,
    timeout: 10 * 1000 // 10 seconds
    });
    });
    $("#calculate-route").submit(function(event) {
    event.preventDefault();
    calculateRoute($("#from").val(), $("#to").val());
    });
    });
    </script>
    <style type="text/css">
    #map {
    width: 500px;
    height: 400px;
    margin-top: 10px;
    }
    </style>
    </head>
    <body>
    <h1>Calculate your route</h1>
    <form id="calculate-route" name="calculate-route" action="#" method="get">
    <label for="from">From:</label>
    <input type="text" id="from" name="from" required="required" placeholder="An address" size="30" />
    <a id="from-link" href="#">Get my position</a>
    <br />
    <label for="to">To:</label>
    <input type="text" id="to" name="to" required="required" placeholder="Another address" size="30" />
    <a id="to-link" href="#">Get my position</a>
    <br />
    <input type="submit" />
    <input type="reset" />
    </form>
    <div id="map"></div>
    <p id="error"></p>
    </body>
    </html>

  7. #7
    Join Date
    Oct 2010
    Location
    Versailles, France
    Posts
    1,264
    To calculate a route, you have only to know that, one a sphere :

    1. The meridian distance (a distance on a longcircle) is 111,111 km for one degree (40 000 km for 360°, it's the meter definition) or 1 852 mètres for one minute (111,111/60 km the nautical mile definition).
    2. The length of a degree of longitude (a distance on a parallele) depends of the radius (or the circumference) at this parallele which is 111,111 * cos(lat) km (or 40 000 * cos(lat) km for the circumference).

    Then the route for a little move (no more than a few degrees) of deltaLat, deltaLng from a Point (lat,lng) is given by an an angle (mesured clokwise from Nord).
    Route = 90° - 180*Math.atan2(deltaLat, Math.cos(lat)*deltaLng)/Math.PI

    For greater distances see As the crow flies or for furter informations the french version Orthodromie.

    NB : Use a developpement console to debug your script. There is an error in your options
    Code:
    var myOptions = {
    zoom: 10,
    center: new google.maps.LatLng(32.794213,-96.618572);// to replace with a comma
    mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    Last edited by 007Julien; 04-05-2013 at 05:51 AM.

  8. #8
    Join Date
    Aug 2012
    Location
    TX
    Posts
    293
    this is what im trying to accomplish

    http://www.ogsolutions.us/aziz/directions.php

    I have a map on this page... your lat and long are auto updated in the header. and when you click directions I want it to convert the lat and long to directions to the waypoint.

    the submit button post to getDirections.php but i have no clue what to put in there...

    Also to get to that page you click the map in the footer and when it loads the big map the map in the footer disappears... if anyone knows up with that I would appreciate it too.

  9. #9
    Join Date
    Aug 2012
    Location
    TX
    Posts
    293
    I think I have all the code. I just dont know how to make it all work together.

    this is code for finding their geolocation

    <html>
    <head>
    <link rel="stylesheet" href="styles/layout.css" type="text/css" />
    <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
    <script type="text/javascript">
    function initGeolocation()
    {
    if( navigator.geolocation )
    {
    // Call getCurrentPosition with success and failure callbacks
    navigator.geolocation.getCurrentPosition( success, fail );
    }
    else
    {
    alert("Sorry, your browser does not support geolocation services.");
    }
    }

    function success(position)
    {

    document.getElementById('lat').value = position.coords.latitude
    document.getElementById('longitude').value = position.coords.longitude;

    }
    function fail()
    {
    // Could not obtain location
    }

    </script>
    #################################################
    and this is code i have on seperate page for putting a roadmap in with a wavepoint.
    #############################################################

    <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
    <script type="text/javascript">
    function initialize() {
    var position = new google.maps.LatLng(32.794213,-96.618572);
    var myOptions = {
    zoom: 10,
    center: position,
    mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    var map = new google.maps.Map(
    document.getElementById("map_canvas"),
    myOptions);

    var marker = new google.maps.Marker({
    position: position,
    map: map,
    title:"Texcom Construction Office."
    });

    var contentString = '<p style="color:black;"><strong>Texcom Construction LLC</br>1426 Mariposa Dr.</br>Mesquite, TX 75150<br/><br/><a href="directions.php">Click For Directions</a></strong></p1>';
    var infowindow = new google.maps.InfoWindow({
    content: contentString
    });

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

    }
    </script>

  10. #10
    Join Date
    Oct 2010
    Location
    Versailles, France
    Posts
    1,264
    It's wont work. I live in Versailles !
    Good luck !
    Last edited by 007Julien; 04-05-2013 at 06:57 AM.

  11. #11
    Join Date
    Nov 2010
    Posts
    1,049
    here is something similar that I made a while ago (so please forgive the ugly coding). If geolocation fails, it falls back on IP lookup. And if the geolocator gets it wrong, you can drag your location or type in a new one. Geolocation isn't working here either (Guatemala), but last time I looked when it was working, the code worked OK. Let me know if you have any questions...

    Code:
    <!DOCTYPE html> 
    <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>Client locator and directions to advertiser</title>
    
    <style>
    html, body {
    height: 100%;
    margin: 0;
    padding: 0;
    }
    #directionsPanel {
    height: 100%;
    float:right;
    width:30%;
    overflow:auto;
    }
    #map_canvas {
    float: left;  
    width:68%;
    height: 100%;
    }
    </style>
     
    </head> 
    <body> 
    
    <div id="map_canvas"></div> 
    <div id="directionsPanel"></div> 
    <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js"></script>
    <script type="text/javascript" src="http://j.maxmind.com/app/geoip.js"></script>
    
    <script type="text/javascript"> 
     var directionsDisplay = new google.maps.DirectionsRenderer();
    
     var directionsService = new google.maps.DirectionsService();
     var map;
     var geocoder;
     var marker = null;
     var infowindow = new google.maps.InfoWindow();
     var infowindow1 = new google.maps.InfoWindow();
     var point;
     var bizAdd;
     var myint;
    
     var geocoder = new google.maps.Geocoder();
     var myOptions = {
     	zoom: 11,
     	mapTypeId: google.maps.MapTypeId.ROADMAP,
     	draggable: false,
     	center: bizAdd
     };
     map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
     directionsDisplay.setMap(map);
     directionsDisplay.setPanel(document.getElementById("directionsPanel"));
     bizAdd = new google.maps.LatLng(32.794213, -96.618572);
     var message = "Texcom Construction LLC</br>1426 Mariposa Dr.</br>Mesquite, TX 75150<br/>";
     createMarker(bizAdd, message);
    
     function createMarker(bizAdd, html) {
     	var contentString = html + '<br><input type="button" value="Show Directions" onclick="getDirs()"></input>';
     	var marker = new google.maps.Marker({
     		position: bizAdd,
     		map: map
    
     	});
    
     	google.maps.event.addListener(marker, 'click', function () {
     		infowindow.setContent(contentString);
     		infowindow.open(map, marker);
    
     	});
     	map.setCenter(bizAdd);
     	google.maps.event.trigger(marker, 'click');
     	map.setOptions({
     		draggable: true
     	});
     }
    
    
     function showBox(address) {
     	newcontent = '<br>Type your address here:<div><input type="text" id="searchbox" style="width:200px"></input><input type="button" value="Find Location" onclick="findLoc()"></input></div>'
     	var div = document.createElement('div');
     	div.innerHTML = '<p>' + address + newcontent + '</p>';
     	infowindow1.setContent(div);
    
     }
    
     function findLoc() {
     	address = document.getElementById("searchbox").value;
     	geocoder.geocode({
     		'address': address
     	}, function (results, status) {
     		if (status == google.maps.GeocoderStatus.OK) {
     			point = results[0].geometry.location
     			calcRoute(point);
    
     		} else {
     			alert("Geocode was not successful for the following reason: " + status);
     		}
     	});
    
     }
    
    
     function getDirs() {
     	// Try W3C Geolocation (Preferred)
     	if (navigator.geolocation) {
     		navigator.geolocation.getCurrentPosition(function (position) {
     			point = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
     			// Use IP lookup
     		}, maxMind)
     	} else {
     		maxMind();
     	}
     };
    
     function maxMind() {
     	var MaxLat = geoip_latitude();
     	var MaxLng = geoip_longitude();
     	point = new google.maps.LatLng(MaxLat, MaxLng);
     	myint = setInterval(function () {
     		if (point) {
     			calcRoute(point)
     		}
     	}, 20);
     }
    
    
     function calcRoute(point) {
     	if (myint) {
     		clearInterval(myint)
     	};
     	infowindow.close();
     	if (marker) marker.setMap(null);
     	geocoder.geocode({
     		'latLng': point
     	}, function (results, status) {
     		if (status == google.maps.GeocoderStatus.OK) {
     			if (results[1]) {
     				address = results[0].formatted_address;
    
     				content = '<br>Wrong location? Drag the marker or click <a href = "#" onclick="showBox(address); return false">here<\/a> to enter your address';
     				infowindow1.setContent('<p>' + address + content + '</p>');
     				var div = document.createElement('div');
     				div.innerHTML = content;
     				infowindow1.setContent(div);
     				infowindow1.setPosition(point);
     				infowindow1.open(map);
    
     			} else {
     				alert("No results found");
     			}
     		} else {
     			alert("Geocoder failed due to: " + status);
     		}
     	});
    
     	var request = {
     		origin: point,
     		destination: bizAdd,
     		travelMode: google.maps.DirectionsTravelMode.DRIVING
     	};
    
     	directionsService.route(request, function (response, status) {
    
     		if (status == google.maps.DirectionsStatus.OK) {
     			var bounds = new google.maps.LatLngBounds();
     			directionsDisplay.setDirections(response);
    
     			google.maps.event.addListener(directionsDisplay, 'directions_changed', function () {
     				infowindow1.setPosition(directionsDisplay.dragResult.routes[0].legs[0].steps[0].start_location);
     			});
    
     		}
    
     	});
     	directionsDisplay.setOptions({
     		suppressInfoWindows: true,
     		infoWindow: infowindow1,
     		draggable: true,
    
     	});
    
     }
    
    </script>
    </body> 
    </html>

  12. #12
    Join Date
    Aug 2012
    Location
    TX
    Posts
    293
    I have it working the best I think I can get it working. I think I can finish it with php

    http://www.webdeveloper.com/forum/sh...on-my-web-page.

    http://www.ogsolutions.us/aziz/directions.php

  13. #13
    Join Date
    Aug 2012
    Location
    TX
    Posts
    293
    The script you sent me is not functional. It shows map and submit button but nothing happens. Nor does it get my location... any ideas?

  14. #14
    Join Date
    Nov 2010
    Posts
    1,049
    Quote Originally Posted by Nicholas Diaz View Post
    The script you sent me is not functional. It shows map and submit button but nothing happens. Nor does it get my location... any ideas?
    oops - you are quite right... I forgot to call the directions function after it gets the location

    try this one. I have added alerts so you can see when it is working with geolocation and when it falls back on IP lookup.

    Some browser notes on geolocation:
    Firefox just fails here (here being where I live), without notification
    Chrome gets the location fine, as long as you give it permission
    IE is crap, so you know what it does...

    Code:
    <!DOCTYPE html> 
    <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>Client locator and directions to advertiser</title>
    
    <style>
    html, body {
    height: 100%;
    margin: 0;
    padding: 0;
    }
    #directionsPanel {
    height: 100%;
    float:right;
    width:30%;
    overflow:auto;
    }
    #map_canvas {
    float: left;  
    width:68%;
    height: 100%;
    }
    </style>
     
    </head> 
    <body> 
    
    <div id="map_canvas"></div> 
    <div id="directionsPanel"></div> 
    <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js"></script>
    <script type="text/javascript" src="http://j.maxmind.com/app/geoip.js"></script>
    
    <script type="text/javascript"> 
     var directionsDisplay = new google.maps.DirectionsRenderer();
    
     var directionsService = new google.maps.DirectionsService();
     var map;
     var geocoder;
     var marker = null;
     var infowindow = new google.maps.InfoWindow();
     var infowindow1 = new google.maps.InfoWindow();
     var point;
     var bizAdd;
     var myint;
    
     var geocoder = new google.maps.Geocoder();
     var myOptions = {
     	zoom: 11,
     	mapTypeId: google.maps.MapTypeId.ROADMAP,
     	draggable: false,
     	center: bizAdd
     };
     map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
     directionsDisplay.setMap(map);
     directionsDisplay.setPanel(document.getElementById("directionsPanel"));
     bizAdd = new google.maps.LatLng(32.794213, -96.618572);
     var message = "Texcom Construction LLC</br>1426 Mariposa Dr.</br>Mesquite, TX 75150<br/>";
     createMarker(bizAdd, message);
    
     function createMarker(bizAdd, html) {
     	var contentString = html + '<br><input type="button" value="Show Directions" onclick="getDirs()"></input>';
     	var marker = new google.maps.Marker({
     		position: bizAdd,
     		map: map
    
     	});
    
     	google.maps.event.addListener(marker, 'click', function () {
     		infowindow.setContent(contentString);
     		infowindow.open(map, marker);
    
     	});
     	map.setCenter(bizAdd);
     	google.maps.event.trigger(marker, 'click');
     	map.setOptions({
     		draggable: true
     	});
     }
    
    
     function showBox(address) {
     	newcontent = '<br>Type your address here:<div><input type="text" id="searchbox" style="width:200px"></input><input type="button" value="Find Location" onclick="findLoc()"></input></div>'
     	var div = document.createElement('div');
     	div.innerHTML = '<p>' + address + newcontent + '</p>';
     	infowindow1.setContent(div);
    
     }
    
     function findLoc() {
     	address = document.getElementById("searchbox").value;
     	geocoder.geocode({
     		'address': address
     	}, function (results, status) {
     		if (status == google.maps.GeocoderStatus.OK) {
     			point = results[0].geometry.location
     			calcRoute(point);
    
     		} else {
     			alert("Geocode was not successful for the following reason: " + status);
     		}
     	});
    
     }
    
    
     function getDirs() {
    	var geoTimeout = 10000;
          var timeOuthandler = setTimeout(maxMind, geoTimeout);
     	// Try W3C Geolocation (Preferred)
     	if (navigator.geolocation) {
     		navigator.geolocation.getCurrentPosition(function (position) {
     			point = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
    		clearTimeout(timeOuthandler);
    		alert("geolocation")
    		calcRoute(point)
     			// Use IP lookup
     		}, function (){maxMind(); clearTimeout(timeOuthandler);})
     	} else {
    	clearTimeout(timeOuthandler);
     		maxMind();
     	}
     };
    
     function maxMind() {
     alert("ip lookup")
     	var MaxLat = geoip_latitude();
     	var MaxLng = geoip_longitude();
     	point = new google.maps.LatLng(MaxLat, MaxLng);
     	myint = setInterval(function () {
     		if (point) {
     			calcRoute(point)
     		}
     	}, 20);
     }
    
    
     function calcRoute(point) {
     	if (myint) {
     		clearInterval(myint)
     	};
     	infowindow.close();
     	if (marker) marker.setMap(null);
     	geocoder.geocode({
     		'latLng': point
     	}, function (results, status) {
     		if (status == google.maps.GeocoderStatus.OK) {
     			if (results[1]) {
     				address = results[0].formatted_address;
    
     				content = '<br>Wrong location? Drag the marker or click <a href = "#" onclick="showBox(address); return false">here<\/a> to enter your address';
     				infowindow1.setContent('<p>' + address + content + '</p>');
     				var div = document.createElement('div');
     				div.innerHTML = content;
     				infowindow1.setContent(div);
     				infowindow1.setPosition(point);
     				infowindow1.open(map);
    
     			} else {
     				alert("No results found");
     			}
     		} else {
     			alert("Geocoder failed due to: " + status);
     		}
     	});
    
     	var request = {
     		origin: point,
     		destination: bizAdd,
     		travelMode: google.maps.DirectionsTravelMode.DRIVING
     	};
    
     	directionsService.route(request, function (response, status) {
    
     		if (status == google.maps.DirectionsStatus.OK) {
     			var bounds = new google.maps.LatLngBounds();
     			directionsDisplay.setDirections(response);
    
     			google.maps.event.addListener(directionsDisplay, 'directions_changed', function () {
     				infowindow1.setPosition(directionsDisplay.dragResult.routes[0].legs[0].steps[0].start_location);
     			});
    
     		}
    
     	});
     	directionsDisplay.setOptions({
     		suppressInfoWindows: true,
     		infoWindow: infowindow1,
     		draggable: true
    
     	});
    
     }
    
    </script>
    </body> 
    </html>
    Last edited by xelawho; 04-08-2013 at 10:57 AM.

  15. #15
    Join Date
    Aug 2012
    Location
    TX
    Posts
    293

    Thanks all

    I have it working. Things to learn from this. Stacking g map api gets tricky. It causes errors.
    Making sure to have your calls set properly such as on load or on click are important. Making the same call twice will cause problems. Such as having a map in your footer.php and your current page. Even referencing the google api in your header twice on two different pages that include on one page is bad. It works it's awesome and I've learned a lot from the past five days of all who contributed

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Tags for this Thread

Posting Permissions

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



Recent Articles