How to get the users location using google maps v3 - google-maps

I have been trying to get the users location using the map v3 and show the path from there location to a fixed destination. But i had no luck finding a solution to get the users location, i have read the API but couldn't figure out anything checked all the examples still the same . hope some one can help me Thanx.

Solution:
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
function initialize() {
var loc = {};
var geocoder = new google.maps.Geocoder();
if(google.loader.ClientLocation) {
loc.lat = google.loader.ClientLocation.latitude;
loc.lng = google.loader.ClientLocation.longitude;
var latlng = new google.maps.LatLng(loc.lat, loc.lng);
geocoder.geocode({'latLng': latlng}, function(results, status) {
if(status == google.maps.GeocoderStatus.OK) {
alert(results[0]['formatted_address']);
};
});
}
}
google.load("maps", "3.x", {other_params: "sensor=false", callback:initialize});

google.loader.ClientLocation only gives a very approximate estimate as to the user's location.
Best choice is to use that as a fallback if HTML5 geolocation is not present, or not allowed by the user.
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(
function(p) {
//get position from p.coords.latitude and p.coords.longitude
},
function() {
//denied or error
//use google.loader.ClientLocation
}
);
} else {
//use google.loader.ClientLocation
}

jQuery('#map_canvas').gmap({ 'zoom':2,'center':new google.maps.LatLng(39.809734,-98.55562), 'callback': function() {
var self = this;
self.getCurrentPosition(function(position, status) {
if ( status === 'OK' ) {
clientlat = position.coords.latitude;
clientlon = position.coords.longitude;
var clientlatlng = new google.maps.LatLng(clientlat, clientlon);
}
});
}});

Related

Google Maps Directions dragged polyline coordinates reset after extending the route

Hey guys, the function of this code is described below.
there are some predefined functions below i.e getMapOption and others
function initialize(){
var divCalcDis = $('divCalcDis');
var pdist = $('pdist');
var pTimeTaken = $('pTimeTaken');
var txtLatLon = $('divLatLon');
var lblDistance = $('lblDistance');
var mapOption = mapHandler.getMapOption(that.LonLatCoordinates[0], 15, "Default");
map = mapHandler.getMap('map_canvas', mapOption);
var renderOption = { draggable: true };
directionsDisplay = new google.maps.DirectionsRenderer(renderOption);
directionsDisplay.setMap(map);
google.maps.event.addListener(directionsDisplay, 'directions_changed', function () { for (i = 0; i < directionsDisplay.directions.routes.length; i++) {
//getting latlon
txtLatLon.innerHTML = "";
console.log(directionsDisplay.directions.routes[i].overview_path.length);
var latLng = directionsDisplay.directions.routes[i].overview_path[k];
var latLng = directionsDisplay.directions.routes[i].overview_path[directionsDisplay.directions.routes[i].overview_path.length - 1].toString();
latLng = latLng.split('(')[1];
latLng = latLng.split(')')[0];
latLng = latLng.split(' ');
latLng = latLng[0] + latLng[1];
txtLatLon.innerHTML += latLng;
}
});
startMap();
}
function startMap() {
var i=0;
google.maps.event.addListener(map, 'click', function (event) {
i++;
if(i === 1){
mapHandler.setMarker(event.latLng, map, "http://www.google.com/intl/en_us/mapfiles/ms/micons/green-dot.png", null, null, null, that.permanentMarkers, false);
that.origin = event.latLng; //comma seperated values of lat,lon
}
else if(i > 1){
mapHandler.setMarker(event.latLng, map, "http://www.google.com/intl/en_us/mapfiles/ms/micons/green-dot.png", null, null, null, that.permanentMarkers, false);
if (i === 2) {
that.dest = event.latLng; //comma seperated values of lat,lon
}
else if (i > 2) {
that.wayPTs.push({
location: that.dest,
stopover: true
});
that.dest = event.latLng;
}
that.calcRoute();
}});
};
function calcRoute() {
var divCalcDis = stringHandler._id('divCalcDis');
var pdist = stringHandler._id('pdist');
var pTimeTaken = stringHandler._id('pTimeTaken');
var txtLatLon = stringHandler._id('divLatLon');
txtLatLon.innerHTML = "";
if (!that.wayPTs.length > 1) {
this.wayPTs = null;
}
var request = this.directionsRequest(this.origin,this.dest,google.maps.DirectionsTravelMode.DRIVING,this.wayPTs,false,true,true,google.maps.DirectionsUnitSystem.METRIC);
that.directionsResponse.route(request, function (response, status) {
//console.log(response);
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
};
**
I am making a project using Google Maps API V3 Directions library in which i am creating a route when a user click some place on the map
Here is a screenshot**
Now when i drag the direction drawn line it works smoothly and giving me the latitude and longitude correctly.
Here is a screenshot
But the Problem is when i click on anyother place on the map(after dragging) the waypoint refreshes and i get the old without drag route with the next stop as you can see below
Here is a Screenshot
How to save the latLon of the waypoint so they are available after creation of new points Thx
You need to push the coordinates into the route array so they will always be available. So push when you drag and push when you click. May be this can be of assistance to you. Best of luck.

HTML5 - What is making this code get the country instead of city?

What is making the following code get the country and not the city, and how can I change it to get the city instead of country?
function get_visitor_country() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position){
var lat = position.coords.latitude;
var lon = position.coords.longitude;
var latlng = new google.maps.LatLng(lat, lon);
geocoder = new google.maps.Geocoder();
geocoder.geocode({'latLng': latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
var country = results[results.length-1].formatted_address;
$("#location-detection .location-name").html(country);
$("#geolocation-worked").css("display", "block");
$("#no-geolocation").css("display", "none");
$geolocation_fix.hide().css({ height : 0 });
init_geolocation_switch();
}
}
});
});
}
}
The script is also loading http://maps.google.com/maps/api/js?sensor=false at the end of the file, if that might be affecting it.
Your script currently is not getting anything special(like a city or a country) , it gets something out of the results.
To get the city search inside the results for an entry with types set to ["locality", "political"]
When you found it you got the city.
Creation of an object labeled with addressTypes for convenient access:
var components={};
jQuery.each(results,function(i,v){
components[jQuery.camelCase(v.types.join('-'))]=v;
})
//test it
alert((components.localityPolitical)
? components.localityPolitical.formatted_address
: 'n/a');
See: Address Component Types

Google Map API to detect user location

I am learning about jquery mobile. I came across a sample code which uses the following google maps api
http://maps.google.com/maps/api/js?sensor=false
And the code is to detect the current location of the user
function getPosition(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
var latlng = new google.maps.LatLng(lat, lng);
var geocoder = new google.maps.Geocoder();
if (geocoder) {
geocoder.geocode({'latLng': latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
//window.alert(results[1].address_components[0].long_name);
var locationVal = results[1].address_components[0].long_name;
var stateVal = results[1].address_components[1].short_name;
var location = document.getElementById('location');
location.value = locationVal;
}
}
});
}
}
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(getPosition);
}
In the above code, in the results array, there is an address_components array. How to determine the properties of the results object and then again the properties of the address_component?
See here: http://code.google.com/apis/maps/documentation/javascript/geocoding.html

How to get the Google Map passing Zone Name?

I want to display the google Map based on zone name. I am getting Zone name in my jsp page (ie. China Lake, California - USA). I need to pass that and display google Map. How to do that through Google javascript API?
Thanks in advance
I found the solution. here is my code:
<script type="text/javascript">
var map = null;
var geocoder = null;
function initialize() {
if (GBrowserIsCompatible()) {
map = new GMap2(document.getElementById("map"));
map.setUIToDefault();
geocoder = new GClientGeocoder();
showAddress("Melapalayam,Tirunelveli,Tamilnadu");
}
}
function showAddress(address) {
if (geocoder) {
geocoder.getLatLng(
address,
function(point) {
if (!point) {
alert(address + " not found");
} else {
map.setCenter(point, 15);
var marker = new GMarker(point, {draggable: true});
map.addOverlay(marker);
GEvent.addListener(marker, "click", function() {
alert(address);
});
}
}
);
}
}
window.onload = initialize;
</script>
Gnaniyar Zubair
Have you tried to pass the zonename as location to the geoCoder's function getLocations ?
Let us know if this has worked.
EDIT: Sorry 1 moment hold on. I will post some listing.
function userLocSearch(location){
userInput = location;
if (GBrowserIsCompatible()) {
geocoder = getGeocoder();
geocoder.getLocations(location, function(responce){
if(responce.Status.code==200){
if(responce.Placemark.length==1){
//just one result
mapInit(responce.Placemark[0].Point.coordinates[1],responce.Placemark[0].Point.coordinates[0],14);
}else{
//more than one result
mapInit(responce.Placemark[0].Point.coordinates[0],responce.Placemark[0].Point.coordinates[1],14);
updateInfoText(responce.Placemark.length);
}
}else{
//error
//no result
geocoder.getLocations("USA", function(responce){
mapInit(responce.Placemark[0].Point.coordinates[1],responce.Placemark[0].Point.coordinates[0],6);
});
}
});
}else{
//TODO
//browser not compartible
}
return false;
}
mapInit is here an other of my functions. The one which initializes the map.
The one I pasted is just for getting the required geocooredinates by a search string

Google Maps API V3 and Local search problem - empty results?

I am trying to implement a Maps API V3 and Local Search but I seem to be having problems. Somehow, the results in the OnLocalSearch() function is empty.
Here is my complete code:
<script type="text/javascript">
//<![CDATA[
$(document).ready(function() {
// do stuff when DOM is ready
var geocoder = new google.maps.Geocoder();
var address = '{{string_location}}';
var map;
// Our global state for LocalSearch
var gInfoWindow;
var gSelectedResults = [];
var gCurrentResults = [];
var gLocalSearch = new GlocalSearch();
if (geocoder) {
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
//alert(results[0].geometry.location.lat())
//alert(results[0].geometry.location.lng())
//Create the Map and center to geocode results latlong
var latlng = new google.maps.LatLng(results[0].geometry.location.lat(), results[0].geometry.location.lng());
var myOptions = {
zoom: 14,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
gLocalSearch.setSearchCompleteCallback(this, OnLocalSearch);
gLocalSearch.execute("{{business_item.name}}");
}
else {
alert('No results found. Check console.log()');
console.log("Geocoding address: " + address);
console.log("Geocoding failed: " + status);
}
});
}
/*
Other functions
*/
function OnLocalSearch() {
if (gLocalSearch.results[0]) { //This is empty. Why?
var resultLat = gLocalSearch.results[0].lat;
var resultLng = gLocalSearch.results[0].lng;
var point = new GLatLng(resultLat,resultLng);
callbackFunction(point);
}else{
alert("not found!");
}
}
});
//]]>
</script>
FYI, I am using this as an example and I am stuck for a few hours now about this: http://gmaps-samples-v3.googlecode.com/svn-history/r136/trunk/localsearch/places.html
Any reply will be greatly appreciated.
Regards,
Wenbert
UPDATE
I made a mistake somewhere here:
<script src="http://www.google.com/uds/api?file=uds.js&v=1.0" type="text/javascript"><;/script>
<script src="http://maps.google.com/maps/api/js?v=3.1&sensor=false&region=PH"></script>
Also, make sure you double check the address you are geocoding. I am from the Philippines and it seems that Google only geocodes Major Roads. See http://gmaps-samples.googlecode.com/svn/trunk/mapcoverage_filtered.html
Thanks to jgeerdes from irc.geekshed.net #googleapis
Just making a couple of tweaks so that the code is actually complete, and using an address I know will be geocoded successfully plus a query I know will return something, your code works. Here is what I did:
<html>
<head>
<title>Wenbert test</title>
<script src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
//<![CDATA[
google.load('jquery','1.4.2');
google.load('maps','3',{other_params:'sensor=false'});
google.load('search','1');
alert('starting...');
$(document).ready(function() {
alert('here');
// do stuff when DOM is ready
var geocoder = new google.maps.Geocoder();
var address = '4019 lower beaver rd. 50310';
var map;
// Our global state for LocalSearch
var gInfoWindow;
var gSelectedResults = [];
var gCurrentResults = [];
var gLocalSearch = new GlocalSearch();
if (geocoder) {
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
//alert(results[0].geometry.location.lat())
//alert(results[0].geometry.location.lng())
//Create the Map and center to geocode results latlong
var latlng = new google.maps.LatLng(results[0].geometry.location.lat(), results[0].geometry.location.lng());
var myOptions = {
zoom: 14,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
gLocalSearch.setSearchCompleteCallback(this, OnLocalSearch);
gLocalSearch.execute("debra heights wesleyan church");
}
else {
alert('No results found. Check console.log()');
console.log("Geocoding address: " + address);
console.log("Geocoding failed: " + status);
}
});
}
/*
Other functions
*/
function OnLocalSearch() {
if (gLocalSearch.results[0]) { //This is empty. Why?
var resultLat = gLocalSearch.results[0].lat;
var resultLng = gLocalSearch.results[0].lng;
var point = new google.maps.LatLng(resultLat,resultLng);
callbackFunction(point);
}else{
alert("not found!");
}
}
});
//]]>
</script>
</head>
<body>
<div id="map_canvas" style="height:100%;"></div>
</body>
</html>