How to retrieve English Results in Google Maps API V3 - localization

//....
directionsDisplay = new google.maps.DirectionsRenderer();
directionsDisplay.setMap(map);
directionsService = new google.maps.DirectionsService();
var request = {
origin : new google.maps.LatLng(origin.lat, origin.lng),
destination : new google.maps.LatLng(destination.lat, destination.lng),
travelMode : google.maps.DirectionsTravelMode.DRIVING,
unitSystem : google.maps.DirectionsUnitSystem.METRIC,
region: 'de'
};
directionsService.route(request, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(result);
}
});
//....
As a result I get something like this
Head southwest on 吳江路/吴江路 toward 泰兴路/泰興路
Turn left at 茂名北路
Continue onto 茂名南路
Turn right at 淮海中路
Slight left to stay on 淮海中路
Turn left at 华山路/華山路
The instructions are English on my browser, and French on my French colleagues French Firefox, the street names are Chinese, I thought I requested information in German region: 'de'
Now ok, maybe the Chinese streets are not available in German, but setting region to gb, en, even zh seems to do nothing.
I really would like the text just to be one language, preferably English.
edit I am quite sure the street names are available in English, because when I use the Geocoder results are in English e.g Shimen Road (No.1)
edit2 with http://maps.google.com/maps/api/js?sensor=false&language=cs I am able to force the instructions into a language, but still the street names are stuck in Chinese. Using the geocoder api i can receive chinese street names that are Chinese translated into English/German/French (with fallback to english when german/french translations are missing) so why the directions street names is stuck on Chinese does not make sense. It could be just a flaw/deliberate on google's side, but I kind of doubt it.
Is there a reason

DirectionRequest doesn't have a parameter to specify language. The language is distinguished according to the language used for the map. The language is either specified as an optional language parameter in the <script> tag e.g.
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&language=cs">
or if the parameter is not present the browser's preferred language is used.
If you want to use different language for the direction results and the map, you can use Google Directions API:
http://code.google.com/apis/maps/documentation/directions/
The result is JSON text. To use it easily, it should be sufficient just to convert it to an object.
The region parameter (both in the maps' DirectionRequest and Directions API) doesn't change the language, it serves other purpose. It affects results to be biased towards some region (e.g. the default result for 'Toledo' is the city in Ohio USA, if you want the one in Spain, use region=es to bias the results).

Related

Java API which return language code from language display name

I have a service which gives the language display name as part of response. I want to retrieve the language code so that I can apply the internationalization for output file.
Expected input : English - United States
Output : en_US
You might use something like that:
Optional<Locale> locale = Arrays.stream(Locale.getAvailableLocales())
.filter(l ->
l.getDisplayLanguage().equals("English") &&
l.getDisplayCountry().equals("United States")
).findAny();
locale.ifPresent(System.out::println);

Fetch Full Address based on Postal Code via Regex

I would like to grab the address highlighted in red. "Site Location:" can be easily identified via match(). However, how can I grab the highlighted part only without going over proceeding content, i.e., "You have applied...etc". Please note that the proceeding content won't always start with "You have applied".
What I would do is the following:
Look for "Site Location:"
Grab anything after "Site Location:" until you find empty/blank new line.
Can anyone help me achieving it in Ruby?
Note that the whole text is stored in a string variable.
regex = /\bSite Location:\s+(.*?)\n\s*\n/m
str = "Site Location: Raglan Street
Collingwood Town, Some County
You have applied..."
if md = regex.match(str)
address = md[1].strip.gsub(/^\s+/,'')
puts address
end
Output:
Raglan Street
Collingwood Town, Some County
Note: one thing to watch for is the possibility of different types of newlines. E.g. Microsoft may use \r\n\r\n, etc. in which case you may have to adjust regex accordingly.

Unable to change say voice in Tropo MVC

I'm using the Tropo MVC classes and have a problem with changing the voice in the say. Setting the voice property of the say object does not seem to change the voice for example:
Say say1 = new Say("This is first voice");
say1.Voice = "susan";
Say say2 = new Say("This is the male voice");
say2.Voice = "dave";
List<Say> sayList = new List<Say>();
sayList.Add(say1);
sayList.Add(say2);
Script.Ask(null, null, new Choices("[1 DIGIT]", "dtmf", "#"), null, strArgs, true, sayList, Convert.ToSingle(action.Timeout));
The voice does not change. In fact it appears that the only way to change the voice is to set Script.Voice = "voice" which doesn't work for me as I have to handle language select in the first Ask which requires English voice followed by French voice.
Tropo also supports SSML, which is a super powerful markup language for mixing voices and adjusting voice tempo/cadence.
You can mix voices in a single Say command by doing something like:
new Say("<?xml version='1.0'?><speak>For English please press 1.<voice name='Carlos' xml:lang='es'>para el español por favor pulse 2</voice></speak>")
The inline XML is kinda yukkie but it gets the job done and learning SSML will allow you to create some really professional-sounding apps.

How to get user's geolocation?

On many sites I saw printed out my current city where I am (eg "Hello to Berlin."). How they do that? What everything is needed for that?
I guess the main part is here javascript, but what everything I need for implementing something like this to my own app? (or is there some gem for Rails?)
Also, I would like to ask for one thing yet - I am interesting in the list of states (usually in select box), where user select his state (let's say Germany), according to the state value are in another select displayed all regions in Germany and after choosing a region are displayed respective cities in the selected region.
Is possible anywhere to obtain this huge database of states/cities/regions? Would be interesting to have something similar in our app, but I don't know, where those lists get...
You need a browser which supports the geolocation api to obtain the location of the user (however, you need the user's consent (an example here) to do so (most newer browsers support that feature, including IE9+ and most mobile OS'es browsers, including Windows Phone 7.5+).
all you have to do then is use JavaScript to obtain the location:
if (window.navigator.geolocation) {
var failure, success;
success = function(position) {
console.log(position);
};
failure = function(message) {
alert('Cannot retrieve location!');
};
navigator.geolocation.getCurrentPosition(success, failure, {
maximumAge: Infinity,
timeout: 5000
});
}
The positionobject will hold latitude and longitude of the user's position (however this can be highly inaccurate in less densely populated areas on desktop browsers, as they do not have a GPS device built in). To explain further: Here in Leipzig in get an accuracy of about 300 meters on a desktop computer - i get an accuracy of about 30 meters with my cell phone's GPS device.
You can then go on and use the coordinates with the Google Maps API (see here for reverse geocoding) to lookup the location of the user. There are a few gems for Rails, if you want. I never felt the need to use them, but some people seem to like them.
As for a list of countries/cities, we used the data obtainable from Geonames once in a project, but we needed to convert it for our needs first.
Internet Service Providers buy up big chunks of IP addresses, so what you're most likely seeing is a backtrace your IP to a known ISP. They have a database with ISP's and their location in the world, so they can try to see where you're from. You could try to use a site like http://www.ipaddresslocation.org/ to do your work. If you look around, there is bound to be a site that lets you enter an IP and get a location, so you just send a POST request to that site with your visitor's IP and scrape the location from the response.
Alternatively you could try to look for an ISP database that has location and what chunks of the IP range they have been allocated. You could probably find one for money, but a free one might be harder to find.
Alternatively, check out this free database http://www.maxmind.com/app/geolite
I've found getCurrentPosition() to often be inaccurate since it doesn't spend a lot of time waiting on the GPS to acquire a good accuracy. I wrote a small piece of JavaScript that mimics getCurrentPosition() but actually uses watch position and monitors the results coming back until they are better accuracy.
Here's how it looks:
navigator.geolocation.getAccurateCurrentPosition(onSuccess, onError, {desiredAccuracy:20, maxWait:15000});
Code is here - https://github.com/gwilson/getAccurateCurrentPosition
Correc syntax would be :
navigator.geolocation.getCurrentPosition(successCallBack, failureCallBack);
Use :
navigator.geolocation.getCurrentPosition(
function(position){
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
console.log("Latitude : "+latitude+" Longitude : "+longitude);
},
function(){
alert("Geo Location not supported");
}
);
If you prefer to use ES6 and promises here is another version
function getPositionPromised() {
function successCb(cb) {
return position => cb(position);
}
function errorCb(cb) {
return () => cb('Could not retrieve geolocation');
}
return new Promise((resolve, reject) => {
if (window.navigator.geolocation) {
navigator.geolocation.getCurrentPosition(successCb(resolve), errorCb(reject));
} else {
return reject('No geolocation support');
}
})
}
And you can use it like this:
getPositionPromised()
.then(position => {/*do something with position*/})
.catch(() => {/*something went wrong*/})
Here is an another api to find out the location in PHP,
http://ipinfodb.com/ip_location_api.php
I have been using geoip.maxmind.com for quite a while and it works 100%. It can be accessed via HTTP requests.

Phonegap/Sencha Language Localization

The Problem:
I'm about to implement language localization to an already very large ipad application that was built using sencha touch wrapped in phonegap. I have the english and spanish translations in json files.
What I'm Planning on Doing:
I plan to load the json files into a sencha touch store, creating a global object. Then in each place where I call text that is displayed, i will replace the text with a call to the global object.
My question(s):
Is there an easier way to implement language localization with my
setup?
Will I run into issues with native sencha stuff (like datepickers)?
When loading/reloading language json files, will I have performance
issues (require a webview reload?, sencha object resizing issues,
etc)
edit 1 : Useful Related Info:
For those going down this road, it quickly becomes useful to write a simple phonegap plugin to get the ipad/iphone device's language setting into your javascript. This requires a plugin, which will look something like this:
Javascript :
part 1:
PhoneGap.exec("PixFileDownload.getSystemLanguage");
part 2(callback Function):
setLanguage(returnedLanguage)
{
GlobalVar.CurrentLanguage = returnedLanguage; //GloablVar.CurrentLanguage already defined
}
Objective C:
-(void)getSystemLanguage:(NSMutableArray*)paramArray withDict:(NSMutableDictionary*)options
{
/*Plugin Details
PhoneGap.exec("PixFileDownload.getSystemLanguage");
Returns Language Code
*/
NSUserDefaults* defs = [NSUserDefaults standardUserDefaults];
NSArray* languages = [defs objectForKey:#"AppleLanguages"];
NSString *language = [languages objectAtIndex:0];
NSLog(#"####### This is the language code%#",language);
NSString *jsCallBack;
jsCallBack = [NSString stringWithFormat:#"setLanguage('%#');",language];
[self.webView stringByEvaluatingJavaScriptFromString:jsCallBack];
}
edit 2: character encoding
When adding additional language characters to a sencha project (or any webview phonegap project), ensure that you have the proper encoding specified in the index file. This is the tag i needed.
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
I've finished this language localization plugin. It's not amazing, but it worked better than I originally speculated. Here are the short answers to each of the questions.
1- Is there an easier way to implement language localization with my
setup?
Not that i'm aware of. The comment by Stuart provided this link Sencha-touch localization. Use a store or a global JSON object? which had some good information on one way that you can use class overrides. I didn't like this approach, because it spread my language translations into different classes. But certainly, if you are doing something simple, or you want something that could be more powerful, perhaps you should investigate that.
2- Will I run into issues with native sencha stuff (like datepickers)?
I ended up specifically leaving "datepickers" in english for now. But everything else was really relatively easy to customize. Almost every graphical UI element can have it's text altered.
3- When loading/reloading language json files, will I have performance
issues (require a webview reload?, sencha object resizing issues,
etc).
The method that i employed (see below) worked exceptionally well in regards to performance. The one issue that you have is right when you switch the languages, you need that specific page to reload. Sencha handled resizing without any flaws, except where I had been foolish and statically set sizes.
Some of what I did was described in edits to the question. Here is a detailed overview of my solution. (warning, it's not the most elegant solution.)
Instead of using a pure JSON file, I ended up just using a javascript function. This isn't the greatest solution because it requires some minimal maintenance, but JSON parsing with phonegap/sencha isn't the best. (I get JSON files from translater's, and quickly paste into the javascript file. Takes around 2 minutes, see further explanation below).
Language.js
function setLanguage(language)
{
if(language == "en")
{
//console.log("inside if Language == en");
GlobalLanguage.CurrentLanguage = language;
GlobalLanguage.ID = {"glossary": [
{
//CONVERTED JSON
about : 'About',
checking_for_updates : 'Checking for updates...(This may take a few minutes.)'
//Any additional translations
}
]};
}
if (language == "es"){
//console.log("inside language == es");
GlobalLanguage.CurrentLanguage = language;
GlobalLanguage.ID = {"glossary": [
{
//CONVERTED JSON
about : 'Acerca de ',
checking_for_updates : 'Verificando actualizaciones... (Capas que demore algunos minutos).'
//Any additional translations
}]};
}
if (language == "pt"){
//console.log("inside language == pt");
GlobalLanguage.CurrentLanguage = language;
GlobalLanguage.ID = {"glossary": [
{
//CONVERTED JSON
about : 'Sobre',
checking_for_updates : 'Verificando se há atualizações... (pode demorar alguns minutos.)'
//Any additional translations
}]};
}
}
As you can see, this file allows for 3 languages (Portugese, English, and Spanish). After setting the language, you could access each localized string anywhere in your object. For example, if you need to access the word "about" simply use:
GlobalLanguage.ID.glossary[0]["about"]
This will access the GlobalLanguage object which will have whatever language loaded into the properties. So throughout your project, you could have these calls. However, I'd recommend taking it one step further
function langSay(languageIdentifier){
// console.log("inside langSay");
if(!GlobalLanguage.ID.glossary[0][languageIdentifier]){
return "[! LANGUAGE EXCEPTION !]";
}
else{
return GlobalLanguage.ID.glossary[0][languageIdentifier];
}
}
This protects you from having language exceptions and having your program crash without knowing where (you may have hundreds or thousands of properties being set in that language.js file). So now simply :
langSay("about")
One additional note about formatting from JSON. The format you want your language files in is:
languageIdentifier : 'Translation',
languageIdentifier : 'Translation',
languageIdentifier : 'Translation'
I used Excel for the formatting. Also the languageIdentifiers are unique identifiers without spaces. I recommend just using Excel to format first 3 to 4 words word1_word2_word3_word4 of the english translation.
word1_word2_word3 : 'word1 word2 word3'
Hope this helps you out! I'd be happy to respond to any questions

Resources