get address line in Arabic from coordinates - dart

Am using Geocoder plugin to get address line, country, postal code, .... like this:
final coordinates = new Coordinates(26.328446, 50.153868);
var addresses = await Geocoder.local.findAddressesFromCoordinates(coordinates);
var first = addresses.first;
print(addresses);
print("${first.featureName} : ${first.addressLine}");
and this returns:
flutter: Zarqa Al Yamamah Street : Zarqa Al Yamamah Street - Al Dana Al Jenobiah, Dhahran 34453, Saudi Arabia
I want to get the same result but in Arabic .. is there is a way to achieve this with this plugin? or there is any other plugins can return address for me in Arabic?

You can get the language code ar or ar-SA. So you need to do this:
Locale loc = new Locale("ar");
Geocoder geocoder = new Geocoder(this, loc);
or this way
geocoder = new Geocoder(this, Locale.ar_SA))
Your code can be like this
Locale loc = new Locale("ar");
Geocoder geocoder = new Geocoder(this, loc))
final coordinates = new Coordinates(26.328446, 50.153868);
var addresses = await Geocoder.local.findAddressesFromCoordinates(coordinates);
var first = addresses.first;
print(addresses);
print("${first.featureName} : ${first.addressLine}");
Do it like this:
Geocoder geocoder;
List<Address> addresses;
geocoder = new Geocoder(this, Locale.ar_SA))
addresses = geocoder.getFromLocation(latitude, longitude, 1); // Here 1 represent max location result to returned, by documents it recommended 1 to 5
String address = addresses.get(0).getAddressLine(0); // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex()
String city = addresses.get(0).getLocality();
String state = addresses.get(0).getAdminArea();
String country = addresses.get(0).getCountryName();
String postalCode = addresses.get(0).getPostalCode();
String knownName = addresses.get(0).getFeatureName(); // Only if available else return NULL
See this example:
import 'package:locales/locales.dart';
import 'package:locales/currency_codes.dart';
import 'package:intl/intl.dart';
void main() {
final locale = Locale.ar_SA;
final currencyCode = CurrencyCode.sar;
final format = NumberFormat.simpleCurrency(
locale: '$locale', name: '$currencyCode', decimalDigits: 2);
print(locale);
print(currencyCode);
print(format.format(123.456));
}
https://github.com/jifalops/locales

If you want to use specific local you must use apiKey
try to replace Geocoder.local method with Geocoder.google in your code
Like this :
Coordinates coordinates = Coordinates(latLng.lat, latLng.lng);
List<Address> addresses =await Geocoder.google(apiKey,language:'ar').findAddressesFromCoordinates(coordinates);
How to get apiKey ? show Get an API Key

Related

Splitting in Dart

How to Spilt this paymentUrl.
const _paymentUrl =
'bitcoin:3QF3iP4PZPw51qB5w6Jpo8j7P4AXyS83ra?amount=0.00107000';
TO Get
{Address: "3QF3iP4PZPw51qB5w6Jpo8j7P4AXyS83ra", Amount: "0.00107000"}
It looks like a URI, and is named like a URI, so try using the Uri class:
const _paymentUrl =
'bitcoin:3QF3iP4PZPw51qB5w6Jpo8j7P4AXyS83ra?amount=0.00107000';
var bcUri = Uri.parse(_paymentUrl);
var address = bcUri.path;
var amount = bcUri.queryParameters["amount"];
var map = {"Address": address, "Amount": amount};
it seems the ? is always there, so you can split it based on it like this:
const _paymentUrl = 'bitcoin:3QF3iP4PZPw51qB5w6Jpo8j7P4AXyS83ra?amount=0.00107000';
List<String> splitPayment = _paymentUrl.split('?');
String bitcoin = splitPayment[0];
String amount = splitPayment[1];

Longitude is always zero in image meta data

I am taking a photo using a MediaPicker in Xamarin. I start the geolocation service and then once the picture is taken I send the byte array of the image and the position information to my own platform specific implementation to add the position information in the meta data of the image.
I then save the image as a file and then email it to myself so I can open it in an external application (Picasa) to ensure the GPS information has been stored properly.
The problem I am running into is that the Latitude and Altitude show up fine, but the Longitude is always zero. I have put break points in my app and verified that the meta data is set properly and that all the information has valid values. I am at a loss at what is going on here.
Some of the following code may be redundant or inefficient simply because I have been testing different methods of adding the meta data. I am using the following code in my application in iOS implementation of this meta data adding method:
public byte[] AddPositionInformation(byte[] bytes, SaleScribe.PCL.Services.Geolocation.Position position)
{
var data = NSData.FromArray(bytes);
UIKit.UIImage original = UIKit.UIImage.LoadFromData(data);
CGImageSource myImageSource = CGImageSource.FromData(original.AsJPEG());
var options = new CGImageDestinationOptions();
options.GpsDictionary = new CoreGraphics.CGImagePropertiesGps();
options.GpsDictionary.Latitude = (float)position.Latitude;
options.GpsDictionary.Longitude = (float)position.Longitude;
options.GpsDictionary.Altitude = (int)position.Altitude;
NSMutableData mutableData = new NSMutableData();
using(var dest = CGImageDestination.Create(mutableData, myImageSource.TypeIdentifier, 1, new CGImageDestinationOptions()))
{
dest.AddImage(myImageSource, (int)(myImageSource.ImageCount - 1), options);
dest.Close();
}
return (mutableData as NSData).ToArray();
}
In the function that receives this byte array I am simply writing the byte array directly to a file.
Any help would be very much appreciated.
Thanks!
For anyone who may interested I had to use another method to get this to work, but the underlying problem was that the GPS Lat and Long require a uint so the -94.xxx longitude was invalid. I needed to add the absolute value of the lat and long and then add the appropriate ref value based on the original signed value.
Here is the code that worked for me:
public byte[] AddPositionInformation(byte[] bytes, SaleScribe.PCL.Services.Geolocation.Position position)
{
var data = NSData.FromArray(bytes);
CGImageSource myImageSource = CGImageSource.FromData(data);
var ns = new NSDictionary();
var imageProperties = myImageSource.CopyProperties(ns, 0);
var gps = new NSMutableDictionary();
gps.SetValueForKey(NSObject.FromObject(System.Math.Abs(position.Latitude)), CGImageProperties.GPSLatitude);
gps.SetValueForKey(NSObject.FromObject(new NSString(position.Latitude < 0 ? "S" : "N")), CGImageProperties.GPSLatitudeRef);
gps.SetValueForKey(NSObject.FromObject(System.Math.Abs(position.Longitude)), CGImageProperties.GPSLongitude);
gps.SetValueForKey(NSObject.FromObject(new NSString(position.Longitude < 0 ? "W" : "E")), CGImageProperties.GPSLongitudeRef);
gps.SetValueForKey(NSObject.FromObject(position.Altitude), CGImageProperties.GPSAltitude);
gps.SetValueForKey(NSObject.FromObject(position.Altitude < 0 ? 1 : 0), CGImageProperties.GPSAltitudeRef);
var mutableDictionary = imageProperties.MutableCopy();
mutableDictionary.SetValueForKey(gps, CGImageProperties.GPSDictionary);
NSMutableData mutableData = new NSMutableData();
var dest = CGImageDestination.Create(mutableData, myImageSource.TypeIdentifier, 1);
dest.AddImage(myImageSource, 0, mutableDictionary as NSDictionary);
dest.Close();
return mutableData.ToArray();
}

Parsing JSON in swift inconsistent

I'm running into what I believe to be a bug. I have an array of objects returned from a server. However, when pulling values out of them I get inconsistent results. Each of these items are in the same array of the response from server:
When I try to pull the quantity value of this one it returns as in Int:
{
address = "4040 MARKET ST RM 226";
city = PHILADELPHIA;
ln = "AMOXICILLIN 500 MG CAPSULE";
ndc = 57237003105;
npi = 1619912375;
"pharmacy_name" = "GRACE PHARMACY INC";
phone = "(215)895-5594";
price = "8.00";
quantity = 500;
state = PA;
vendor = una;
zip = 19104;
}
However, when I try to pull quantity from this one, it's returned as a String.
{
address = "1826 Chestnut St # 30";
brand = G;
city = Philadelphia;
distance = "0.06";
latitude = "39.951747";
ln = "AMOXICILLIN 500 MG CAPSULE";
longitude = "-75.171154";
"ncpdp_id" = 3969485;
ndc = 65862001705;
"pharmacy_hours_of_operation" = "Open 24 Hours";
"pharmacy_name" = "CVS PHARMACY";
phone = "(215)972-0909";
price = "11.82";
quantity = 30;
state = PA;
vendor = scriptsave;
zip = "19103-4902";
}
Why in the world would this be occurring? Both objects seems to be identical except for some extra values in one.
===
Serializing the JSON like this:
let searchResultsJSON: NSDictionary = try NSJSONSerialization.JSONObjectWithData(jsonData, options: .MutableContainers) as! NSDictionary
Grabbing the values like this:
quantity = formDictionary["quantity"] as? Int
quantityString = formDictionary["quantity"] as? String
====
Here is the JSON:
results = (
{
address = "4040 MARKET ST RM 226";
city = PHILADELPHIA;
ln = "ESOMEPRAZOLE MAG DR 40 MG CAP";
ndc = 13668015510;
npi = 1619912375;
"pharmacy_name" = "GRACE PHARMACY INC";
phone = "(215)895-5594";
price = "74.00";
quantity = 1000;
state = PA;
vendor = una;
zip = 19104;
},
{
address = "1700 Market St";
brand = G;
city = Philadelphia;
distance = "0.22";
latitude = "39.952981";
ln = "ESOMEPRAZOLE MAG DR 40 MG CAP";
longitude = "-75.168431";
"ncpdp_id" = 3985059;
ndc = 00378235193;
"pharmacy_hours_of_operation" = "S(Clsd) M(8a-6p) T(8a-6p) W(8a-6p) T(8a-6p) F(8a-6p) S(9a-12p)";
"pharmacy_name" = "PICKWICK PHARMACY INC";
phone = "(215)563-4860";
price = "241.23";
quantity = 30;
state = PA;
vendor = scriptsave;
zip = "19103-3913";
}
);
So here, quantity in the first one is returned as an Int and as a String in the second one. I beginning to think this is a server side issue...
===
Looking at the JSON in Chrome does confirm that it's an encoding error from the server. Thanks #CouchDeveloper
Apple's API's for JSONSerialization are a bit nasty for usage in Swift.
If your happy to make use of third-party frameworks, SwiftyJSON will help with handling JSON in a type safe manner in swift. It's available as a Cocoapod, using Carthage or even Swift's own package manager.
You can then ensure you get non-nil Integer or String objects like so:
let name = json["name"].stringValue
let number = json["number"].intValue
Or you can handle non-existent values as optionals like so:
let name = json["name"].string
let number = json["number"].int

Parse Json using SwiftyJson

I am able to get the entire JSon array parsed. It outputs to console with no issue. I can't seem to get the individual params from the array... my json looks like:
[{
City = NYC;
Device = "<null>";
DisplayAs = "Steve Hutson";
FirstName = Steve;
LastName = Hutson;
MobilePhone = "000-000-0000";
Org = "<null>";
Region = "";
Role = INSPECTOR;
SupervisorID = "73990";
email = "email#email.com";
fLast = shutson;
"gz_modtimestamp" = "2015-07-28 14:42:41";
id = 96;
isActive = YES;
lastupdated = "<null>";
sendemail = 1;
token = "<null>";
userpassword = "xxx";
},{
City = DET;
Device = "<null>";
DisplayAs = "Filipe Washington";
FirstName = Filipe;
LastName = Washington;
MobilePhone = "000-000-0000";
Org = "<null>";
Region = "";
Role = INSPECTOR;
SupervisorID = "6567";
email = "email#email.com";
fLast = shutson;
"gz_modtimestamp" = "2015-07-28 13:02:09";
id = 93;
isActive = YES;
lastupdated = "<null>";
sendemail = 1;
token = "<null>";
userpassword = "xxx";
}]
In my main ViewController.swift file my json request looks like:
var myData:NSData = getJSON("http://xxxx/getusersData.php")
var myDict:NSArray = parseJSON(myData)
println(myDict)
This prints my entire json object which is perfect. However my issue is, how do I get only the FirstName's in an array? By index this works:
println(myDict[0]["FirstName"]) how ever, it only brings back one item.
I am trying to insert specific json items into sqlite which i am using SQLite.swift but i need to know how to retrieve specific item parameters as I would if i was using AJAX.
I am trying to retrieve FirstName, Email and UserPassword info.
Any help would be appreciated.
You can iterate over the JSON object and retrieve that info:
for (index: String, subJson: JSON) in json {
//Do something you want
var firstName = subJson["FirstName"].stringValue
var email = subJson["email"].stringValue
var userPassword = subJson["userpassword"].stringValue
// Build the sqlite query with the variables here
}
As a clarification, you don't access the values directly as in json["FirstName"], you must also use the type functions from SwiftyJSON. In your case they're both strings, so stringValue is used. If you needed and int, it'd be intValue.
There's also the option of just json["FirstName"].string in case the field is optional. Take a look at the readme

Get City, State, Country from Latitude and Longitude in Google Sheets

In Google Sheets, I have a column with latitude and longitude coordinates. The list goes from A2:A1000. I also have columns for City, State, and Country in B1, C1, and D1, respectively. Is there a formula or script I can run that reads the coordinates and provides the city, state, and country in their respective column? I do not know how to use JavaScript, XML, JSON, serialized PHP, etc. so if your suggestion includes one of those, please provide some instructions. Thanks in advance.
Well, I have a psuedo-solution. Go into Google Spreadsheets > Tools > Script Editor and paste the following code into a blank project:
function reverse_geocode(lat,lng) {
Utilities.sleep(1500);
var response = Maps.newGeocoder().reverseGeocode(lat,lng);
for (var i = 0; i < response.results.length; i++) {
var result = response.results[i];
Logger.log('%s: %s, %s', result.formatted_address, result.geometry.location.lat,
result.geometry.location.lng);
return result.formatted_address;
}
}
Then in the spreadsheet, use this formula:
=reverse_geocode(latitude_goes_here,longitude_goes_here)
For example, if I have the latitude in A2 and longitude in B2:
=reverse_geocode(A2,B2)
This will provide the full address. I'm now trying to figure out how to parse the country from the address.
Based on #gabriel-rotman solution.
Go into Google Spreadsheets > Tools > Script Editor and paste the following code into a blank project:
/**
* Return the closest, human-readable address type based on the the latitude and longitude values specified.
*
* #param {"locality"} addressType Address type. Examples of address types include
* a street address, a country, or a political entity.
* For more info check: https://developers.google.com/maps/documentation/geocoding/intro#Types
* #param {"52.379219"} lat Latitude
* #param {"4.900174"} lng Longitude
* #customfunction
*/
function reverseGeocode(addressType, lat, lng) {
Utilities.sleep(1500);
if (typeof addressType != 'string') {
throw new Error("addressType should be a string.");
}
if (typeof lat != 'number') {
throw new Error("lat should be a number");
}
if (typeof lng != 'number') {
throw new Error("lng should be a number");
}
var response = Maps.newGeocoder().reverseGeocode(lat, lng),
key = '';
response.results.some(function (result) {
result.address_components.some(function (address_component) {
return address_component.types.some(function (type) {
if (type == addressType) {
key = address_component.long_name;
return true;
}
});
});
});
return key;
}
Then in the spreadsheet, use this formula:
=reverseGeocode(address_type; latitude_goes_here; longitude_goes_here)
For example, if I have the latitude in A2 and longitude in B2 and that I want to get the city then I can use:
=reverseGeocode("locality"; A2; B2)
If you want the country you can use:
=reverseGeocode("country"; A2; B2)
Bonus function to extract part of an address:
/**
* Return the closest, human-readable address type based on the the address passed.
*
* #param {"locality"} addressType Address type. Examples of address types include
* a street address, a country, or a political entity.
* For more info check: https://developers.google.com/maps/documentation/geocoding/intro#Types
* #param {"Amsterdam"} address The street address that you want to geocode,
* in the format used by the national postal service
* of the country concerned. Additional address elements
* such as business names and unit, suite or floor
* numbers should be avoided.
* #customfunction
*/
function geocode(addressType, address) {
if (typeof addressType != 'string') {
throw new Error("addressType should be a string.");
}
if (typeof address != 'string') {
throw new Error("address should be a string.");
}
var response = Maps.newGeocoder().geocode(address),
key = "";
response.results.some(function (result) {
return result.address_components.some(function (address_component) {
return address_component.types.some(function (type) {
if (type === addressType) {
key = address_component.long_name;
}
});
});
});
return key;
}

Resources