Google Map API to detect user location - google-maps

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

Related

Google Maps API Geocode - return GPS coordinations [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 4 years ago.
I've got this code:
var get_lat = function(address) {
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
console.log('lat is: '+ results[0].geometry.location.lat());
return results[0].geometry.location.lat();
}
});
}
var get_lng = function(address) {
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
console.log('lng is: '+ results[0].geometry.location.lng());
return results[0].geometry.location.lng();
}
});
}
In console it prints the coordinates I need, but the return value is always undefined:
I use it in classic initialize for Google Maps like this:
function createMarker(latlng) {
var marker = new google.maps.Marker({
position: latlng,
map: map,
});
}
function initialize() {
var myOptions = {
zoom: 8,
center: new google.maps.LatLng(49.210366,15.989588)
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var address = "Correct address that console.logs the correct GPS coordinations in function definitions above";
var gps_lat = get_lat(address);
var gps_lng = get_lng(address);
console.log('GPS lat: ' + gps_lat); // logs "undefined"
console.log('GPS lng: ' + gps_lng); // logs "undefined"
var marker = createMarker({lat: gps_lat}, lng: gps_lng});
}
$(window).on("load", function (e) {
initialize();
});
Do you have any idea why the function consoles the right value but it doesn't return anything?
For GMAP API I use this script: http://maps.google.com/maps/api/js?sensor=false&libraries=geometry
You have the return inside an anonymous function that you pass to geocoder.geocode, all in yet another function (get_lat/get_lng). get_lat/get_lng themselves don't have a return statement, and thus return undefined.
Furthermore, geocoder.geocode will call your anonymous function asynchronously. Which means that there is no chance for get_lat/get_lng to get hold of the return value and return it where get_lat/get_lng was called.
One solution (the simplest one) is to put the createMarker code in the callback for geocoder.geocode. Also, in this case you will have to merge your two get_lat/get_lng functions. Example:
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var gps_lat = results[0].geometry.location.lat()
var gps_lng = results[0].geometry.location.lng();
console.log('lat is ' + gps_lat + '. lng is ' + gps_lng);
var marker = createMarker({lat: gps_lat, lng: gps_lng});
return results[0].geometry.location.lat();
}
});
You have to wait until Google API gives response. So write a logic to create marker in callback function of Google API as shown below.
var getLatLng = function (address)
{
geocoder.geocode({ 'address': address }, function (results, status)
{
if (status == google.maps.GeocoderStatus.OK)
{
var location = results[0].geometry.location;
// Create marker once you get response from Google
createMarker({ lat: location.lat(), lng: location.lng() });
}
});
}
and call that function as shown below
function initialize()
{
var myOptions =
{
zoom: 8,
center: new google.maps.LatLng(49.210366, 15.989588)
}
map = new google.maps.Map(document.getElementById("map"), myOptions);
var address = "Correct address that console.logs the correct GPS coordinations in function definitions above";
// Old code ------------------------------------------------
//var gps_lat = get_lat(address);
//var gps_lng = get_lng(address);
//console.log('GPS lat: ' + gps_lat); // logs "undefined"
//console.log('GPS lng: ' + gps_lng); // logs "undefined"
//var marker = createMarker({ lat: gps_lat, lng: gps_lng });
// ----------------------------------------------------------
// New code
getLatLng(address);
}
and you will get marker on a map

Could not centralise the google map after location search in angular 2

I have a input field and a button. On click of button the location whatever written in the input field will set a marker in google map. I am able to locate a marker in map. But it wont appear in the centre. In fact map will stay constant whatever the location you search.
getAddress(place:Object) {
this.markers = [];
var address = this.step1Data.map_address;
if (!address) return false;
var geocoder = new google.maps.Geocoder();
var that = this;
geocoder.geocode({ 'address': address }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var location = results[0].geometry.location;
var lat = location.lat();
var lng = location.lng();
that.markers.push({
lat: lat,
lng: lng,
label: 'A',
draggable: false
})
that._googleMapsApi.setCenter(location);
}
});
}
setCenter() method is not working here. May I know the reason. googleMapsApi is imported from angular2-google-maps/core.

Issue with google map API

I have to translate a google map api code from v2 to v3. I've tried but it is not working.
This is the old version code:
function getQueryVariable(variable){
var query = window.location.search.substring(1);
var vars=query.split("&");
for(var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if (pair[0] == variable) {
return pair[1];
}
}
}
var map = null;
var geocoder = null;
function showAddress(address, year1,year2,year3) {
map = new GMap2(document.getElementById("map_canvas"));
geocoder = new google.maps.Geocoder();
if (geocoder) {
geocoder.getLatLng(address,function(point) {
if (!point) {
alert(address + " not found");
} else {
map.setCenter(point, 11);
var marker = new GMarker(point);
map.addOverlay(marker);
}
}
);
}
}
This is what I wrote:
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if(decodeURIComponent(pair[0]) {
return pair[1];
}
}
}
var map = null;
var geocoder = null;
function showAddress(address) {
var map=new google.maps.Map(document.getElementById("map_canvas"));
geocoder = new google.maps.Geocoder();
geocoder.geocode(address, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var center = results[0].geometry.location;
map.setCenter(center);
var marker = new google.maps.Marker({
map: map,
position: center
});
}
}
}
Someone can tell me what I'm doing wrong?
Thanks a lot.
Marcello
There are syntax errors in your code. But the main issue is you need to initialize the google.maps.Map object. Currently there are 3 required options in the google.maps.MapOptions object:
https://developers.google.com/maps/documentation/javascript/reference#MapOptions
center | LatLng | The initial Map center. Required.
mapTypeId | MapTypeId | The initial Map mapTypeId. Required.
zoom | number | The initial Map zoom level. Required.
This works for me:
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if(decodeURIComponent(pair[0])) {
return pair[1];
}
}
}
var map = null;
var geocoder = null;
function showAddress(address) {
var map=new google.maps.Map(document.getElementById("map_canvas"),{center:new google.maps.LatLng(0,0), zoom:2, mapTypeId : google.maps.MapTypeId.ROADMAP});
geocoder = new google.maps.Geocoder();
geocoder.geocode({address:address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var center = results[0].geometry.location;
map.setCenter(center);
if (results[0].geometry.viewport) map.fitBounds(results[0].geometry.viewport)
else if (results[0].geometry.bounds) map.fitBounds(results[0].geometry.bounds)
var marker = new google.maps.Marker({
map: map,
position: center
});
} else alert("Geocoder returns: " + status);
});
}
working example

How to get the users location using google maps v3

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);
}
});
}});

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