
Question:
You could see View example (directions-simple.html).
In the above example from and to is given by the user but i'm trying to get <strong>From</strong> automatically by detecting the user location through browser and <strong>To</strong> is been inputted by user.
I tried this dpaste.com/695949 but could not get it working.
Thanks in advance!!
Answer1:You've got a number of JavaScript errors in your example at <a href="http://dpaste.com/695949" rel="nofollow">http://dpaste.com/695949</a>. I cleaned up the core of it, getting the geolocation and setting the map center there. I think you can then go from there to figure out the directions piece, but basically you'll need to have an input box for your user to enter the location they want to go to, and you can use the current map center as the starting point for your directions.
var directionDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
function mapinit(position){
directionsDisplay = new google.maps.DirectionsRenderer();
var chicago = new google.maps.LatLng(41.850033, -87.6500523);
var myOptions = {
zoom:7,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: chicago
}
map = new google.maps.Map(document.getElementById("mapcont"), myOptions);
directionsDisplay.setMap(map);
initiate_geolocation()
}
function initiate_geolocation() {
navigator.geolocation.getCurrentPosition(handle_position_results);
}
function handle_position_results(position){
newCenter = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
map.setCenter(newCenter);
}
Answer2:Sure, just ask the browser where the user is, through the <a href="http://dev.w3.org/geo/api/spec-source.html" rel="nofollow">W3 Geolocation API Specification</a>. Since this may changes across different browser and devices, I'd try with a library like <a href="http://code.google.com/p/geo-location-javascript/" rel="nofollow">geo-location-javascript</a>.