How to use locationFromAddress in flutter - flutter

String _address = ""; // create this variable
void _getPlace() async {
List<Placemark> newPlace = await _geolocator.placemarkFromCoordinates(_position.latitude, _position.longitude);
// this is all you need
Placemark placeMark = newPlace[0];
String name = placeMark.name;
String subLocality = placeMark.subLocality;
String locality = placeMark.locality;
String administrativeArea = placeMark.administrativeArea;
String postalCode = placeMark.postalCode;
String country = placeMark.country;
String address = "${name}, ${subLocality}, ${locality}, ${administrativeArea} ${postalCode}, ${country}";
print(address);
setState(() {
_address = address; // update _address
});
how to replace placemarkFromCoordinates() to locationFromAddress() because convert the address from user input field then change to get the long and lat. Please help me thenks!

You can do both from address to coordinates and vice versa.(with older flutter version & without null safety you can use this)
1st way using geocoding
Future<void> getGeoCoderData() async {
List<Location> locations =
await locationFromAddress("Gronausestraat 710, Enschede");
debugPrint("Address to Lat long ${locations.first.latitude} : ${locations.first.longitude}");
List<Placemark> placemarks =
await placemarkFromCoordinates(52.216653, 6.9462204);
debugPrint("Lat Long to Address: ${placemarks.first.street} : ${placemarks.first.locality}");
}
Output:
2nd way using geocoder
import 'package:geocoder/geocoder.dart';
// From a query / address
final query = "1600 Amphiteatre Parkway, Mountain View";
var addresses = await Geocoder.local.findAddressesFromQuery(query);
var first = addresses.first;
print("${first.featureName} : ${first.coordinates}");
// From coordinates to address
final coordinates = new Coordinates(1.10, 45.50);
addresses = await Geocoder.local.findAddressesFromCoordinates(coordinates);
first = addresses.first;
print("${first.featureName} : ${first.addressLine}");

Related

flutter googlemap get address

I want to fetch address to show on google map. I can only do address with lat,lng. Name of home address, road, sub-district, city, but I tried many ways and it's not showing up. Please help.
I'll have it written in the else section.
#override
void initState() {
findLocation();
super.initState();
}
LatLng centerMap = LatLng(1232,213123, 123.123213);
void findLocation() async {
var lat = double.tryParse(searchitems[0].address![widget.index].latitude.toString());
var lng = double.tryParse(searchitems[0].address![widget.index].longitude.toString());
if (lat != null && lng != null) {
centerMap = LatLng(lat, lng);
} else {
}
print("map:$centerMap");
}
If you want to get address by lattiude and longitude then you can use Google's API for finding the address.
For that, first you have to generate a key from Google Cloud Platform and enable the Geocoding API from it. Then you can fetch address this way:
getAddressFromLatLng(context, double lat, double lng) async {
String _host = 'https://maps.google.com/maps/api/geocode/json';
final url = '$_host?key=$mapApiKey&language=en&latlng=$lat,$lng';
if(lat != null && lng != null){
var response = await http.get(Uri.parse(url));
if(response.statusCode == 200) {
Map data = jsonDecode(response.body);
String _formattedAddress = data["results"][0]["formatted_address"];
print("response ==== $_formattedAddress");
return _formattedAddress;
} else return null;
} else return null;
}
Now if you want to get lat-long by address, you can do it in following way. You can add this package called geocoder:
(from source)
import 'package:geocoder/geocoder.dart';
// From a query
final query = "1600 Amphiteatre Parkway, Mountain View";
var addresses = await Geocoder.local.findAddressesFromQuery(query);
var first = addresses.first;
print("${first.featureName} : ${first.coordinates}");
There's also a package called geocoding(link). You can try that too.

Flutter_contacts update contacts function

I'm quite new to flutter/dart and working in Flutterflow, where trying to create a custom function that takes as input data about the contact in the app (name, surname, cell number, email, photo) and then updates/creates this contact in the user's phone using the next logic:
if a user has a contact with the same name (displayName), then it updates this contact
if a user has a contact with the same phone number, then it updates this contact
if there is no match based on two parameters before, then new contact is created
So far, I have only managed to create a function that checks displayName match, updates contact if there is a match, and if there is no match, it creates a new contact. But I don't know how to do the cell number match/update part (it doesn't work in my code).
The way I'm doing the search for the right contact to update is through the search of contact ID using lists of contacts' names and contacts' IDs to index the right ID when I found the necessary name. It's probably a very ugly and inefficient way to do it, but I don't know the other way.
Will be super happy if someone could give advice on the contact search/update part and overall code optimization (cause I think my approach is long and inefficient). Thank you!
My code is below:
import 'package:flutter_contacts/flutter_contacts.dart';
import 'dart:typed_data';
import 'package:flutter/services.dart';
Future updateContactOnPhone(
String name,
String surname,
String cellnumber,
String email,
String photo,
) async {
String searchingParameterName = name + " " + surname;
String searchingParameterCellphone = cellnumber;
List<String> phoneContactsIDs = [];
List<String> phoneContactsNames = [];
List<String> phoneContactsNumbers = [];
Uint8List bytes = (await NetworkAssetBundle(Uri.parse(photo)).load(photo))
.buffer
.asUint8List();
if (await FlutterContacts.requestPermission()) {
List<dynamic> contacts = await FlutterContacts.getContacts();
contacts.forEach((contact) {phoneContactsIDs.add(contact.id);});
contacts.forEach((contact) {phoneContactsNames.add(contact.displayName);});
contacts.forEach((contact) {if (contact.phones != null) {
phoneContactsNumbers.add(contact.phones.first);}
{phoneContactsNumbers.add("");}});
if (phoneContactsNames.contains(searchingParameterName)) {
int index = phoneContactsNames.indexOf(searchingParameterName);
String contactID = phoneContactsIDs.elementAt(index);
dynamic contact = await FlutterContacts.getContact(contactID);
contact.name.first = name;
contact.name.last = surname;
contact.phones = [Phone(cellnumber)];
contact.emails = [Email(email)];
await contact.update();
} else if (phoneContactsNumbers.contains(searchingParameterCellphone)) {
int index = phoneContactsNumbers.indexOf(searchingParameterCellphone);
String contactID = phoneContactsIDs.elementAt(index);
dynamic contact = await FlutterContacts.getContact(contactID);
contact.name.first = name;
contact.name.last = surname;
contact.phones = [Phone(cellnumber)];
contact.emails = [Email(email)];
await contact.update();
} else {
final newContact = Contact()
..name.first = name
..name.last = surname
..phones = [Phone(cellnumber)]
..emails = [Email(email)]
..photo = bytes;
await newContact.insert();
}}}
I tried various combinations of the code and searched for similar examples on forums, but nothing helped.
This is the code I wrote that worked for me. Hope it'll help someone.
import 'package:flutter_contacts/flutter_contacts.dart';
import 'dart:typed_data';
import 'package:flutter/services.dart';
import 'package:collection/collection.dart';
Future updateCreateContact(
String name,
String surname,
String cellnumber,
String email,
String photo,
) async {
String searchingName = name + " " + surname;
Uint8List bytes = (await NetworkAssetBundle(Uri.parse(photo)).load(photo))
.buffer
.asUint8List();
if (await FlutterContacts.requestPermission()) {
List<Contact> contacts = await FlutterContacts.getContacts(
withProperties: true, withPhoto: true);
Contact? contact = contacts.firstWhereOrNull((c) =>
c.displayName == searchingName ||
c.phones.toString().replaceAll(RegExp(r"\D"), "") == cellnumber);
if (contact != null) {
contact.name.first = name;
contact.name.last = surname;
contact.phones = [Phone(cellnumber)];
contact.emails = [Email(email)];
contact.photo = bytes;
await contact.update();
} else {
final newContact = Contact()
..name.first = name
..name.last = surname
..phones = [Phone(cellnumber)]
..emails = [Email(email)]
..photo = bytes;
await newContact.insert();
}
}
}

The operator '[]' isn't defined for the type 'Object'. Try defining the operator '[]' for Flutter

I am trying to store my database value into a class, but i was unable to convert it into my class using DataSnapshot. I have already added all necessary null safety operators. But it still shows an error.
class User {
String userID = "";
String name = "";
String phoneNo = "";
String email = "";
String password = "";
User(
{required this.userID,
required this.name,
required this.phoneNo,
required this.email,
required this.password});
User.fromSnapshot(DataSnapshot dataSnapshot) {
userID = dataSnapshot.key!;
if (dataSnapshot.value != null) {
name = dataSnapshot.value!["name"] as String;
email = dataSnapshot.value!['email'];
phoneNo = dataSnapshot.value!['phone'];
password = dataSnapshot.value!['password'];
}
}
}
I am trying to define the snapshot value as a String but also the same as others.
Error message
try
if (dataSnapshot.value != null) {
final data = dataSnapshot.value as Map;
name = data["name"] as String;
email = data['email'] as String;
phoneNo = data['phone'] as String;
password = data['password'] as String;
}
Try to specify the type of your DataSnapshot:
User.fromSnapshot(DataSnapshot<Map<String,dynamic>> dataSnapshot) {
userID = dataSnapshot.key!;
if (dataSnapshot.value != null) {
name = dataSnapshot.value!["name"] as String;
email = dataSnapshot.value!['email'];
phoneNo = dataSnapshot.value!['phone'];
password = dataSnapshot.value!['password'];
}
}

How to Convert latitude and Longitude to Address by using Location Plugin in Flutter

I'm using Location library to get the latitude and longitude
https://pub.dev/packages/location
Location location = new Location();
var latitude = "";
var longitude = "";
LocationData _locationData;
_locationData = await location.getLocation();
latitude = _locationData.latitude.toString();
longitude = _locationData.longitude.toString();
But how can i convert this latitude and longitude to address.
Use geocoder :
final coordinates = new Coordinates(latitude, longitude);
addresses = await Geocoder.local.findAddressesFromCoordinates(coordinates);
first = addresses.first;
print("${first.featureName} : ${first.addressLine}");
You can use Nominatim, which is a free open-source geocoding API. It's recommended to setup your own server, but you can use their public API if you abide by their usage policy.

Get id of last Rest API POST using Entity Framework

I need to be able to access the id of a new Post. I will be using this id to populate another field called LocationId like this: "L" + id = LocationId (example L22) where 22 is the id of the new Post. Here is the code for my Post request:
private async void BtnSubmit_Clicked(object sender, EventArgs e)
{
var imageArray = FilesHelper.ReadFully(file.GetStream());
file.Dispose();
var location = new Models.Location()
{
LocationName = EntName.Text,
ImageArray = imageArray,
};
ApiServices apiServices = new ApiServices();
bool response = await apiServices.PostLocation(location);
bool response2 = await apiServices.InputLocationId(id, location);
if (!response || !response2)
{
await DisplayAlert("Alert", "Something wrong", "Cancel");
}
else
{
await DisplayAlert("Hi", "Your record has beed added successfully", "Alright");
}
await Navigation.PushAsync(new SetupPage());
This is on the client side. I have all the APIs created (such as PostLocation and InputLocationId)on Azure SQL Server. This is for a mobile inventory app built using Xamarin.
public async Task<bool> PostLocation(Location location)
{
var json = JsonConvert.SerializeObject(location);
var httpClient = new HttpClient();
var content = new StringContent(json, Encoding.UTF8, "application/json");
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", Settings.AccessToken);
var wimsApiUrl = "http://xxxxxxx.azurewebsites.net/api/Locations";
//Get the Body of the Post
var body = await httpClient.PostAsync(wimsApiUrl, content);
//Convert it to a string
var jString = await body.Content.ReadAsStringAsync();
//Place it in a JSON Object
JObject joResponse = JObject.Parse(jString);
//Parse the JSON Object into an Int from a String
var id = int.Parse(joResponse["Id"].ToString());
//This is used in my other script to Put the LocationId of Lxx
AddNewLocationPage.NewLocationId = id;
return body.IsSuccessStatusCode;
}
My Post Location API:
// POST: api/Locations
[ResponseType(typeof(Location))]
public IHttpActionResult PostLocation([FromBody] Location location)
{
string userId = User.Identity.GetUserId();
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var stream = new MemoryStream(location.ImageArray);
var guid = Guid.NewGuid().ToString();
var file = String.Format("{0}.jpg", guid);
var folder = "~/Content/Images";
var fullPath = String.Format("{0}/{1}", folder, file);
var response = FilesHelper.UploadPhoto(stream, folder, file);
if (response)
{
location.ImagePath = fullPath;
}
var newLocation = new Location()
{
LocationName = location.LocationName,
User = userId,
ImagePath = location.ImagePath
};
db.Locations.Add(newLocation);
db.SaveChanges();
return Ok(new { newLocation.Id});
}
I will then take the id and put it in this Put Request to create the LocationId:
public async Task<bool> InputLocationId(int id, Location location)
{
var json = JsonConvert.SerializeObject(location);
var httpClient = new HttpClient();
var content = new StringContent(json, Encoding.UTF8, "application/json");
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", Settings.AccessToken);
var wimsApiUrl = "http://xxxxxxx.azurewebsites.net/api/Locations/InputLocationId/";
var completeUrl = String.Format("{0}{1}", wimsApiUrl, id);
var response = await httpClient.PutAsync(completeUrl, content);
return response.IsSuccessStatusCode;
}
The InputLocationId API will automatically create the LocationId. Here is my API:
// PUT: api/Locations/5
[HttpPut]
[ResponseType(typeof(void))]
[Route("api/Locations/InputLocationId/{id}")]
public IHttpActionResult InputLocationId(int id, [FromBody] Location location)
{
//string userId = User.Identity.GetUserId();
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var result = db.Locations.FirstOrDefault(locationId => locationId.Id == id);
var resultant = String.Format("L{0}", id);
location.LocationName = location.LocationName;
result.LocationId = resultant;
db.SaveChanges();
return Ok("The record has been updated");
}
I am simply stuck on how to access that id!
// get the response body
var body = await httpClient.PostAsync(wimsApiUrl, content);
// load it into a JSON object using Newtonsoft
JObject data = JObject.Parse(body);
// get the id
var id = int.Parse(data["id"]);
The returns need to be converted into a string from the HttpResponseMessage.
var body = await httpClient.PostAsync(wimsApiUrl, content);
var jString = await body.Content.ReadAsStringAsync();
Then we can place it into a JSON Object:
JObject joResponse = JObject.Parse(jString);
Now this JSON Object can be parsed into an Int. Note it needs to be converted to a string.
var id = int.Parse(joResponse["Id"].ToString());