Google maps api, gecode. Trying to geocode a language specific address - javascript

I'm sure this question has been asked somewhere, but for the life of me i can't seem to find it..
I have an address in "København S" denmark, that i am trying to geocode so i can place a marker on my map. However i get the zero results error, and i can see that
"København S"
has been changed to
"København S"
with the hex.
I'm sure this is fairly easy to get around, but i have been trying the past hour and i think im making it to complicated for myself. Is there an easy workaround to specify the character set i want it to use rather than it being in partly hex?
Here is my code, the error msg and the msg with the hex.
function geocodeAddress() {
var geocoder = new google.maps.Geocoder();
if (geoIndex < addressesToGeo.length) {
var addressSplit = addressesToGeo[geoIndex].split("SPLIT"); // temp
alert(addressSplit[0]); // second alert msg image
geocoder.geocode({ 'address': addressSplit[0] }, makeCallBack(parseInt(addressSplit[1])));
++geoIndex;
}
else {
clearInterval(geoTimer);
}
}

Related

How to detect when a user enters an invalid location to a Google Places field?

I have a form that contains a text field that is connected to the Google Places API. What I want to happen is that, when a recognized address is entered, I also get the lat/long location of the entered place and bash the values into other form fields, so that they can be saved on the backend without another API call. The following initialization code, along with a few debugging logs, is working fine for this (apologies for the stupid field IDs; I blame Drupal...)
function placesInitialize() {
var input = document.getElementById('edit-field-google-location-und-0-value');
var autocomplete = new google.maps.places.Autocomplete(input);
google.maps.event.addListener(autocomplete, 'place_changed', function () {
var geocoder = new google.maps.Geocoder();
var address = document.getElementById('edit-field-google-location-und-0-value').value;
geocoder.geocode({ 'address': address }, function (results, status) {
console.log('inside geocoder.geocode');
if (status == google.maps.GeocoderStatus.OK) {
var latitude = results[0].geometry.location.lat();
var longitude = results[0].geometry.location.lng();
console.log('lat and long = ' + latitude + ' and ' + longitude);
$('#edit-field-location-latitude-und-0-value').val(latitude);
$('#edit-field-location-longitude-und-0-value').val(longitude);
}
else {
console.log('GeocoderStatus not ok:');
console.log(google.maps.GeocoderStatus);
}
});
});
}
google.maps.event.addDomListener(window, 'load', placesInitialize);
Now, if the user enters something that is not recognized by Places, I want to clear the lat and long fields. That's where my problem is: how do I detect that this has happened? I had thought that this would have been signaled by google.maps.GeocoderStatus being not OK, but those logs never fire. In fact, the "inside geocoder.geocode" message doesn't show up in this situation, either.
I've looked, but haven't yet found an event that google.maps might throw in this situation. I could hang something off the input field's blur event, but I'm not sure what it would do (there would be stuff in the input field, just not valid stuff). I thought about having a semaphor that tracks whether the geocoder has been invoked, but I'd still need to detect the "invalid entry" state to catch the case where the user first enters something valid and then replaces it with something invalid.
Anyway: Any thoughts out there? Thanks!
place_changed is still fired even when a suggested location is not selected and "free text" is given. If there is no place found in the geocoder, then the place.address_components will be empty and you can detect that:
autocomplete.addListener('place_changed', fillInAddress);
function fillInAddress() {
var place = autocomplete.getPlace();
if(!place.address_components) {
// then place doesn't exist
}
}
place_change only fires when a user selects one of the suggestions in the dropdown. When the places-library doesn't return suggestions, nothing will happen.
As the Autocomplete doesn't provide access to the the suggestions at all(unless you select one), you may request the suggestions via the Autocomplete-Service(then you'll be able to check if there are any suggestions).
The Autocomplete-functionality you may implement then on your own based on the returned suggestions(e.g. via jQueryUI)

Delete/move Google maps marker (jquery-ui-maps)

I want to remove one marker from my Google Map, but I can't seem to get it to work. I find various answers, all telling me to use .setMap(null) on the marker, but I can't seem to get it to work.
$map_canvas = $('#map_canvas');
var youreHere_Marker;
function centerMapToAddress( address ) {
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if( typeof youreHere_Marker!=="undefined"){
youreHere_Marker.setMap(null);
}
youreHere_Marker = $map_canvas.gmap('addMarker', {'position': results[0].geometry.location.lat()+','+results[0].geometry.location.lng(), 'bounds': true});
}
});
}
I get TypeError: youreHere_Marker.setMap is not a function. To my knowledge this means that the variable youreHere_Marker doesn't have the method .setMap(), but if I do console.log(youreHere_Marker) and inspect the object, I can see the method.
I have more markers on my map, via the MarkerClusterer. Those should remain untouched
I have the feeling I'm close, could someone point me in the right direction?
Edit: I've also tried .setPosition(), same error. I'm assuming I'm using the variable incorrect, but I don't know how to refer to it properly.
Well, i was working with google maps without jQuery, but i think (i'm not sure, but you may try) that you should get your marker with the following code:
youreHere_Marker = $map_canvas.gmap('get', 'markers')[0];
youreHere_Marker.setMap(null);
I'm really not sure that it will do what you want, but there is a possibility that this will work : )
I hope you'll solve you problems.
Thanks. : )

Javascript skipping lines when trying to geocode location

I'm trying to use this function to geocode a string passed to it into a google maps result.
function codeAddress(address) {
var firstResult;
geocoder.geocode( { 'address': address}, function(results, status) {
if(status == google.maps.GeocoderStatus.OK) {
firstResult = results[0];
} else {
firstResult = "failed";
}
});
return firstResult;
}
The problem is that when I try to debug it using the debugger from chrome and insert a breakpoint outside and inside the ceocoder.geocode statement, I can clearly see the program execution go at the third line, but it skips the inner lines and goes straight to the return value (returning an undefined value). Some other times, it goes through the if statement within it, but it doesn't go to the return statement although I have set up a breakpoint there.
Am I trying to do this the wrong way? How can I fix this?
I found some possible answers on StackOverflow, they might help:
Aleem Saadullah on SO posted:
Finally figured it out. It was a silly error. I had linked my Javascript file before linking the jQuery. The code works fine now.
Mikko Ohtamaa answered on SO:
To be strict, whatever custom CGI you are using does not conform
JavaScript syntax.
What I suggest is that you make your custom dynamic processing into
JavaScript comments, so that it doesn't affect the normal JavaScript
parsing. This is much easier than writing your custom JavaScript
parser to cater your custom syntax.
E.g.
// %import and other custom commands here
The best approach is that you would not put any non-JavaScript to JS
files at all. If you need importing and such there are some more
generic JavaScript solutions for them.
http://browserify.org/
http://requirejs.org/
EDIT 2:
Found an answer on Engineer's answer on SO:
geocoder.geocode works asynchronously, so you need to wait until its
response will be delivered from google's servers, and only then use
responded data. Put your loop inside of callback:
geocoder.geocode( { 'address': zip }, function(results, status) { // status is empty
if (status == google.maps.GeocoderStatus.OK) {
var userLat = results[0].geometry.location.lat();
var userLng = results[0].geometry.location.lng();
userLatLng = results[0].geometry.location;
for (var i = data.length-1; i--;) {
//loop body
}
}});//end geocode

How to make a "did you mean" link with suggestions, in google maps api?

I'm trying to make a web application with google maps api, that gives directions. Right now, It gives directions fine unless the user types in something wrong, it either doesn't show anything or it tries to figure it out and gives the wrong address. I want to make functionality where if the address is not recognized it has "did you mean" and then make a suggestion that's close to what you were trying to enter. I couldn't find anything in the google code that talked about that, but I'm wondering if anyone knows if it's possible, and how I can do it?
Thanks!
loadFromWayPoints() draws polyline only if the inputs provided to it maps to any definite point on the earth. You can avoid the confusion to function by fixing your from point in form of latitude and longitude, instead of address. Then using following function you may create Did you mean for To point if multiple points returned for toInput.
Code is self explanatory. If you dont understand. Reply in comment.
One of the point you want to plot should return definite point from google geocoder system.
In my I used the from point as definite point. And had it coordinates with me. So there is no chance of getting
geo.getLocations(toInput, function (result){
//map.clearOverlays();
if (result.Status.code == G_GEO_SUCCESS) {
// ===== If there was more than one result, "ask did you mean" on them all =====
if (result.Placemark.length > 1) {
document.getElementById("textualdirectionscontainer").innerHTML = "Did you mean:";
// Loop through the results
for (var i=0; i<result.Placemark.length; i++) {
var p = result.Placemark[i].Point.coordinates;
document.getElementById("textualdirectionscontainer").innerHTML += "<br>"+(i+1)+": <a href='javascript:place(" +p[1]+","+p[0]+")'>"+ result.Placemark[i].address+"<\/a>";
}
}
// ===== If there was a single marker =====
else {
document.getElementById("textualdirectionscontainer").innerHTML = "";
var p = result.Placemark[0].Point.coordinates;
toLatLang = new GLatLng(p[1], p[0]);
// place(p[1],p[0]);
directionsPanel = $('textualdirectionscontainer');
directionsPanel.getElements('div').each(function(item) {
item.dispose();
});
directions.clear();
directions.loadFromWaypoints([hotelLatLng.toString(), toLatLang.toString()], {getPolyline:true});
/*var gp = directions.getPolyline();
map.addOverlay(gp); */
}
}
});

Center Google Map Based on geocoded IP

Basically whenever someones opens up my (Google) map I want it default to their approximate location.
Is there an easy way to do it with Google's API or do I have to write a custom code (this is python based app)?
You can use Google API's built-in ClientLocation object:
if (GBrowserIsCompatible())
{
var map = new google.maps.Map2(document.getElementById("mapdiv"));
if (google.loader.ClientLocation)
{
var center = new google.maps.LatLng(
google.loader.ClientLocation.latitude,
google.loader.ClientLocation.longitude
);
var zoom = 8;
map.setCenter(center, zoom);
}
}
Check out http://www.ipinfodb.com/. You can get a latitude and longitude value by passing their services an IP address. I did something recently where I created a simple service that grabbed the current IP address and then passed it to the service ("api/location/city" is just a service that curls the ipinfodb service). Using jquery:
$.get("api/location/city", null, function(data, textStatus)
{
if (data != null)
{
if (data.Status == "OK")
{
var lat = parseFloat(data.Latitude);
var lng = parseFloat(data.Longitude);
$.setCenter(lat, lng, $.settings.defaultCityZoom);
manager = new MarkerManager(map, {trackMarkers : true });
var e = $.createUserMarker(map.getCenter());
e.bindInfoWindowHtml($("#marker-content-event").html());
var m = [];
m.push(e);
// map.addOverlay(e);
manager.addMarkers(m, 10);
manager.refresh();
}
else
{
$.setCenter($.settings.defaultLat, $.settings.defaultLng, $.settings.defaultZoom);
}
}
}, "json");
The key here is this line:
$.setCenter(lat, lng, $.settings.defaultCityZoom);
Just setting the center to the lat/lng of the result of the service call.
Per the docs, just map.setCenter(new GLatLng(37.4419, -122.1419), 13); or whatever other coordinates. Doing it in the page's Javascript is normally preferred.
If you mean translating an IP to lat and long, I don't think the Google API supports that, but there are other web services that do, such as maxmind, hostip, and many, many others. I don't know which one(s) to recommend -- try out a few, would be my suggestion!
If the user uses FireFox 3.5/google gears, you can retrieve the lat and lng from the browser itself.
You'll find details on another stackoverflow post here
IP Address Geocoding API for Google Maps: http://web3o.blogspot.com/2011/06/ip-address-geocoding-api-for-google.html

Categories

Resources