Can't create a Maps Coordinate [duplicate] - google-maps

I've been doing mobile part of my project after "completing" the web part. I'm using google map api. I have coded following:
function codeAddress() {
var image = 'images/tickmark1.png';
var address = document.getElementById('address').value;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var markerZad = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
title: "NEW TASK",
icon: image
});
document.getElementById('latitude').value =results[0].geometry.location.nb.toPrecision(9);
document.getElementById('longitude').value=results[0].geometry.location.ob.toPrecision(9);
document.getElementById('adrs').value=document.getElementById('address').value;
document.getElementById('latit').value =results[0].geometry.location.nb.toPrecision(9);
document.getElementById('longit').value=results[0].geometry.location.ob.toPrecision(9);
alert("Ustalono wspolrzedne nowego zadania. Wybierz pracownika \n (PPM usuwa znacznik)");
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
google.maps.event.addListener(markerZad, 'click', function() {
alert("Nowe zadanie: \n"+ address + "\n"+"Wybierz pracownika \n (PPM usuwa znacznik)");
map.setZoom(14);
map.setCenter(this.getPosition());
});
google.maps.event.addListener(markerZad, 'rightclick', function() {
markerZad.setMap(null);
document.getElementById('latitude').value =0;
document.getElementById('longitude').value=0;
document.getElementById('adrs').value=0;
document.getElementById('latit').value =0;
document.getElementById('longit').value=0;
document.getElementById('ajdideva').value="X";
document.getElementById('iddev').value=0;
document.getElementById('baton').disabled=true;
alert("Usunieto znacznik. Wpisz inny adres.");
});
});
}
Let's leave behind the level of this code. I'm sure it's a bad one. But the thing is...it used to work for me like few days ago. Now it doesn't. And yes, I haven't touched it since then... I figured out myself, that the problem causes "results". I get status==OK, then it places a marker in a correct spot, and then...nothing happens. I mean my inputs in html file don't get their values changed and +listeners aren't working. When I changed "results[0]." etc to simple string, it worked, that's why I think that there's a problem with results[0]. Any suggestions please?

Don't access undocumented properties like e.g. results[0].geometry.location.nb . The names of these properties may(and will) change. To access the values of these properties use the documented methods, e.g. lat() to access the latitude of a LatLng-instance:
document.getElementById('latitude').value
= results[0].geometry.location.lat().toPrecision(9);

Related

How to get the event on changing the selected route displaying in a google render container?

Here is the code :
var map = new google.maps.Map(document.getElementById("map_canvas"), $scope.map_options);
var dirService= new google.maps.DirectionsService();
var dirRenderer= new google.maps.DirectionsRenderer()
var dirContainer=document.getElementById('dir-container');
var showDirections = function(dirResult, dirStatus) {
if (dirStatus != google.maps.DirectionsStatus.OK) {
alert('Directions failed: ' + dirStatus);
return;
}
// Show directions
dirRenderer.setMap(map);
dirRenderer.setDirections(dirResult);
dirRenderer.setPanel(dirContainer);
};
dirService.route( {origin: '158 cours tolstoi, villeurbanne',
destination: '8 cours andré philip, villeurbanne',
travelMode: google.maps.DirectionsTravelMode.DRIVING,
provideRouteAlternatives: true }
, showDirections);
I would like to catch the event of selecting another route between the route displaying in the dirContainer.
The alternatives route are displaying in the dirContainer and because provideRouteAlternatives: true.
The event
google.maps.event.addListener(dirRenderer, 'directions_changed',
function() {
alert('a');
});
is not fired when you change the alternative route.
In advance thanks.
UPDATE
from this post in the v3 API group
There is no event. There is a feature request to add that to the API:
https://code.google.com/p/gmaps-api-issues/issues/detail?id=3565
There should be a routeIndex_changed event, but that doesn't seem to work (and isn't documented). routeindex_changed does work, but I don't see it in the documentation.
http://www.geocodezip.com/v3_SO_simpleMap_directions_changed.html
Here is the event :
google.maps.event.addListener(dirRenderer, 'routeindex_changed',
function() {
alert(dirRenderer.getRouteIndex());
});

gmaps4rails methods - Gmaps.map.centerMapOnUser() and Gmaps.map.markers.length

Two questions here, but they're related. Is there a way to make the centerMapOnUser() action smooth? I have a marker that denotes my location, and it's draggable.
// watch for marker movement, and update location accordingly
function updateUserLocation(latLng) {
var revGeo = new google.maps.Geocoder();
revGeo.geocode({'latLng': latLng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
$('#loc').html(results[1].formatted_address);
}
} else {
alert("Geocoder failed due to: " + status);
}
});
Gmaps.map.userLocation = latLng;
Gmaps.map.centerMapOnUser();
lat = latLng.lat();
lng = latLng.lng();
}
This is very abrupt, and almost disorienting, though. I was wondering if anyone knew of a way to make it a smooth transition.
Side question. Sometimes the map shows 1 marker, sometimes it shows 26 (A-Z). If it's only 1, the zoom level is set to max. I disabled auto_zoom and added this function:
function zoom() {
if (Gmaps.map.markers.length == 1) {
//only one marker, choose the zoom level you expect
Gmaps.map.serviceObject.setZoom(16);
}
else{
//more than one marker, let's auto_zoom
Gmaps.map.map_options.auto_zoom = true;
Gmaps.map.adjustMapToBounds();
}
}
Checking the console, Gmaps.map.markers always returns 0, whether there are 0, 1, or several markers. Markers get added initially, though, and even added later on through the replaceMarkers() function, so everything seems to be configured proper.

How to extract latitude and longitude from Google Maps autocomplete

I'm building an web app that uses this code to search for addresses:
http://code.google.com/intl/en/apis/maps/documentation/javascript/examples/places-autocomplete.html
Type there, New York, NY.
So, when the map is loaded in the DOM after the user using the autocomplete option, the user can save the Location Address in the database, and it will be available as it is "ex. New York, NY". But, for the application I need to save also the Latitude and Longitude.
But I have no ideia how to grab them from the Google API.
As a test app, I'm still using the google code.
I guess I should create some HIDDEN fields and assign the latitude and longitude to them as the user chooses the Address.
Any implementation for my problem is welcome!!
Thanks in advance
P.S:
As I'm new in StackOverflow I could't answer myself.
So I'm editing the post, as suggested by stackoverflow, and here is the solution based in Daniel's answer and some researches in the Google Api:
function getLatLng( address )
{
var geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address' : address }, function( results, status ) {
if ( status == google.maps.GeocoderStatus.OK ) {
var mapLatLng = document.getElementById( 'mapLatLng' ); // mapLatLng is my hidden field, use your own
mapLatLng.value = results[0].geometry.location.lat() + ', ' + results[0].geometry.location.lng();
} else {
alert( "Geocode was not successful for the following reason: " + status );
}
});
}
Daniel is right for the most part, where he is incorrect is his access of the property here:
$('#latitude').val(results[0].geometry.location.Pa)
$('#longitude').val(results[0].geometry.location.Qa)
You should instead use the lat() and lng() functions provided:
$('#latitude').val(results[0].geometry.location.lat())
$('#longitude').val(results[0].geometry.location.lng())
You can use the Google API to get the Longitude and Latitude from your address.
As you already said, you should implement a hidden field where the result should be inserted.
Then you can save the location together with the coordinates.
I recently implemented this function in one of my projects:
function getLatLngFromAddress(city, country){
var address = city +", "+ country;
var geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
$('#latitude').val(results[0].geometry.location.lat());
$('#longitude').val(results[0].geometry.location.lng());
} else {
console.log("Geocode was not successful for the following reason: " + status);
}
});
}

Android Emulator - how to get Geo Location?

I am using 'jquery-ui-map' for an android app. My emulator is Google API Level 13 version 3.2. My Javascript code is :
$('#gps_map').live("pageshow", function() {
$('#map_canvas_2').gmap('refresh');
$('#map_canvas_2').gmap('getCurrentPosition', function(position, status) {
if ( status === 'OK' ) {
var latlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude)
$('#map_canvas_2').gmap('get', 'map').panTo(latlng);
$('#map_canvas_2').gmap('search', { 'location': latlng }, function(results, status) {
if ( status === 'OK' ) {
$('#from').val(results[0].formatted_address);
}
});
} else {
alert('Unable to get current position');
}
});});
This code always fails to get location. I can't see the GPS icon in the emulator. I tried setting all possible permissions, tried setting the latlong coordinates with geo fix method but nothing works. Is there ANY way by which geo location can work on android ?
Finally found the answer to this.
$('#map_canvas').gmap('getCurrentPosition', function(pos, status) {
if (status === "OK") {
var latLng = new google.maps.LatLng(pos.coords.latitude,pos.coords.longitude);
$('#map_canvas').gmap('option', 'center', latLng);
} else {
// error msg
}
}, { timeout: 10000, enableHighAccuracy: true} );
Adding a longer timout in options, like shown above fixes the issue. The example shows a long timeout: 10 seconds.

Google Maps geocode: undefined latitude

Hitting a page with the follow script displays:
lat: undefined
lon: 51.5001524
Why is it that while lat is undefined, lon is not?
A working example can be found here.
Pull up your web console and see for yourself!
$(document).ready(function(){
var geocoder;
function codeAddress()
{
geocoder = new google.maps.Geocoder();
var address = 'London, England';
geocoder.geocode({'address': address}, function(results, status)
{
if (status == google.maps.GeocoderStatus.OK)
{
lat = results[0].geometry.location.Ia;
lon = results[0].geometry.location.Ja;
console.log("lat: " + lat);
console.log("lon: " + lon);
}
});
}
codeAddress();
});
</script>
</head>
<body>
</body>
</html>
While we're at it - what is the historical significance of Ia and Ja? I presume it relates to the Cartesian unit vectors i and j (predominately used in Engineering) though I'm not sure.
I found other examples online who use .lat for .Ia and .lng for .Ja
These, however, are returning in the console:
function () {
return this[a];
}
Just need a kick in the right direction.
Thank you.
I would use lat() and lng():
var lat = results[0].geometry.location.lat();
var lng = results[0].geometry.location.lng();
This is a designed behaviour of the geocoder: google shifts the identifiers in
geometry.location.Ia;
geometry.location.Ja;
on a weekly basis, i.e. from above to
geometry.location.Ja;
geometry.location.Ka;
and so on, so it is not possible to refer by id to the geocoder result object.
Chances are Google are using a javascript minifier (e.g. http://jscompress.com/) which renames all variables - hence they're subject to change on every build.