I am trying to get pincode for longitude and latitude using google location services. I used geocoder to get the Address Object. I see that in for some address getPostalCode is Null but postal code can be seen in the address lines.
How do I get the postal code in this case? Should i use regex to get it?
Based from this documentation, you need to specify the restriction by using the componentRestrictions parameter and can be filter by postalCode or country.
The following example function demonstrates using the componentRestrictions parameter to filter by country and postalCode:
function codeAddress() {
geocoder.geocode({
componentRestrictions: {
country: 'AU',
postalCode: '2000'
}
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
window.alert('Geocode was not successful for the following reason: ' + status);
}
});
}
You can check this example in GitHub.
Related
how to get the latitude and longitude by search location names with open street map osmdroid.
My Expectation is, It looks like implement google map places autocomplete, but I don't know how to make autocomplete places in osmdroid. I am not found any tutorial for search locations by location name with osmdroid
so I found this way to search location with osmdroid, but it's not what I expected. I am using geocoder to search the location here the reference
https://developer.android.com/reference/android/location/Geocoder
In the first step we need to make a search box Edittext to search the location and make the logic looks like this.
etSearch.setOnEditorActionListener { _, actionId, _ ->
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
etSearch.clearFocus()
val query = etSearch.text.toString()
if (query != "") {
getLocationName(query)
} else {
Toast.makeText(
requireContext(),
getString(R.string.mohon_isi_terlebih_dahulu),
Toast.LENGTH_SHORT
).show()
}
}
true
}
after getting the query text from the search box we need to call function getLocationName(String) and the function looks like this
fun getLocationName(locationName: String){
try {
val geocoder = Geocoder(requireContext(), Locale.getDefault())
var geoResults: List<Address> = geocoder.getFromLocationName("$locationName", 1)
if (geoResults.isNotEmpty()) {
val addr = geoResults[0]
val location = GeoPoint(addr.latitude, addr.longitude)
moveCameraMap(location)
}else{
Toast.makeText(requireContext(),"Location Not Found",Toast.LENGTH_LONG)
}
} catch (e: java.lang.Exception) {
print(e.message)
}
}
in the function we can see the geocoder call getFromLocationName("location name", max result), and we got the lat and long.
It's my solution and I hope someone can make it better. thanks for your help
I could really use some help improving the accuracy of the Geofencing feature. If you look at the following screenshots you can see my location and the location of circle and marker which share the same latLng coordiantes and radius as my geofence.
Link to the image
If I run the following lines within the app.js file:
const taskName = "front_door";
const latLng = { latitude: -37.820711, longitude: 144.994264 };
const radius = 5;
Permissions.askAsync(Permissions.LOCATION);
Location.startGeofencingAsync(taskName, [
{
...latLng,
radius
}
]);
TaskManager.defineTask(taskName, task => {
if (task.data.eventType === Location.GeofencingEventType.Enter) {
console.log("entered");
}
console.log(task.data.region.state);
return;
});
Which is returning entered and 1 (explanation).
Given my current location being outside of the geofence I would expect entered to fire only once I had inside of the geofence and task.data.region.state to equal 2 (explanation).
If I change:
const latLng = { latitude: -37.820711, longitude: 144.994264 };
To:
const latLng = { latitude: -37, longitude: 144 };
The geofence is far enough away that entered is never output and the task.data.region.state equals 2.
This leads me to believe that the issue is related to the accuracy set of Location however, I cannot find a way to increase the accuracy when using the startGeofencingAsync method.
If I was not using geofencing I would do something like this:
Location.startLocationUpdatesAsync(taskName, {
accuracy: Location.Accuracy.Highest
});
But I can't see how to access the options object when using Location.startGeofencingAsync(taskName, regions)
If you know how to achieve this please do let me know as I am pulling my hair out over it! Thanks in advance :)
I am creating an Android App , an Uber Clone. In this I am using Firebase to list the rides created by the user.
The Ride stored in the following format .
{
"category" : "NUVO",
"driverids" : "",
"drop_lat" : "40.7127753",
"drop_long" : "-74.0059728",
"estdate" : "Wed#Feb#28th",
"estmile" : "4.19",
"esttime" : "01:02#PM",
"esttotalfare" : "4.61",
"fareest" : "1.1",
"g" : "t9z83wv46x",
"l" : [ 40.674426, -73.944033 ],
"notes" : "Gv",
"orgin_lat" : "145 Brooklyn Ave, Brooklyn, NY 11213, USA%20New York, NY, USA",
"request_id" : "5a75579740d166e95b8b4567",
"requested_category" : "FAM_SUV",
"rider_id" : "5a507bf340d16660288b4567",
"status" : 1,
"trip_id" : 0
}
Now I am Using GeoFire's GeoQuery's queryAtLocation to pick all rides with in 5 KMs from his current location.
The query uses the lat & lang from the field "l" and compare it with the current location lat & lang of the driver.
If the list's lat & lang is within 5 KMs , it will return the key , that is the parent name of the child "l".
Now I am currently in India. I use Lockito App to fix a Mock GPS location in India. After that I create a Ride within 5 KMs radius.
Now , the ride successfully listed in the drivers list. No Problem.
My Issue
But When I fix a mock GPS location in USA , this flow not working. I fixed the driver location on Brookyln Childeren's Museum and also created a ride on the same museum. But GeoQuery not calling onKeyEntered . It simply exists after calling GeoQueryReady function .
I check my current Lat & Lang from the app and it returns as 40.67434763453142,-73.94402358680964. I checked this against the lat&lang on field "l" .(refer above JSON). Both pointing to same location.
But GeoQuery failed to retrieve it
My Question
Why this issue happening ?. If I use India's locations. Geoquery works perfectly .
But why it failing in USA.
You may tell ,"There will be an issue in lockito". But Lockito returning correct location lat lang . I checked it in Logcat. And , if there is a issue in Lockitto then How it working in India.
Here My GeoQoery Code :
try {
showDialog();
double nearByDistanceRadius = 5.00d;
com.firebase.geofire.GeoFire geoFire = new com.firebase.geofire.GeoFire(FirebaseDatabase.getInstance().getReference().child(childtype));
final com.firebase.geofire.GeoQuery geoQuery = geoFire.queryAtLocation(new GeoLocation(latitude, longitude), nearByDistanceRadius);
geoQueryEventListener=new GeoQueryEventListener() {
#Override
public void onKeyEntered(final String key, GeoLocation location) {
Toast.makeText (getApplicationContext(), "The key is = ",Toast.LENGTH_LONG).show();
}
#Override
public void onKeyExited(final String key) {
System.out.println("ON KEYEXITED"+key);
}
#Override
public void onKeyMoved(String key, GeoLocation location) {
System.out.println("ON KEYMOVED"+key);
}
#Override
public void onGeoQueryReady() {
System.out.println("ON KEYQUERYREADY");
#Override
public void onGeoQueryError(DatabaseError error) {
System.out.println("ON KEYERROR"+error);
}
};
geoQuery.addGeoQueryEventListener(geoQueryEventListener);
} catch (Exception e) {
e.printStackTrace();
}
Above , except onGeoQueryReady , no method called if I use USA. But it's
working in India. Can anyone tell me why that is the case?
This maybe long gone n dusted but perhaps can help others.
Since u mention its mock GPS coordinates. and u probably manually entered them.
GeoFire uses a special g: "code" (10 digit code) which is area wise / city wise
if you use the same g code in the same city / country (India in ur case) it will work fine !
However,if you use the same code in another country , geoQuery will fail. To make it work. u need to add one line in your code
geoFire.SetLocation() and someone in USA needs to run that code once only. geoFire will save a special key in g: "" Location. After you have the key you can remove that line from your app.
You can use that key generated by geoFire to manually enter as many locations as you want in USA and geoQuery will always work on that !!! Make sure you use the same pattern as geoFire does.
g:
l:
0:
1:
It took a while but I figured. It's that buggy geofire dependency. Downgrade from 3.0.0 to 2.3.1 solved it.
This my code:
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
List<Address> addresses = geocoder.getFromLocationName(text, 10);
test.clear();
for (int i = 0; i < addresses.size(); i++) {
Address address = addresses.get(i);
for (int j=0;j<address.getMaxAddressLineIndex();j++) {
test.add(address.getAddressLine(j) + ", " + address.getCountryName());
// address.getLatitude();
// address.getLatitude();
}
}
But I can't find something like address.getPlaceID().
Maybe I use another API get PlaceID from name, or lat, long from above code. Thanks!
Look at this docs.
You will get the lat,long,name for the Address
and then call this below google api
https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=-33.8670522,151.1957362&radius=500&types=food&name=cruise&key=YOUR_API_KEY
You will get a response like this
{
"html_attributions" : [],
"results" : [
{
"geometry" : {
"location" : {
"lat" : -33.870775,
"lng" : 151.199025
}
},
...
"place_id" : "ChIJrTLr-GyuEmsRBfy61i59si0",
...
}
],
"status" : "OK"
}
For there you will get the place-id.
Note: Please enable the GeoLocation Api from Google Developer Console otherwise it return the error msg :This API project is not authorized to use this API.
You also can use direct search instead of nearbysearch
https://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&key=YOUR_API_KEY
Look at Getting Started with Geocoding
Both of the proposed ways cost money and I think peoples should mention it. We have the -$200 from the Google, but its all depends from how much users you have and how frequent you need to use the geocode. 60k requests per month to the geocoder - easy $300 only for to use the geocode https API :
Nov 1 – 30, 2018
Geocoding API Geocoding: 6073 Counts - $30.38
Dont filter what you need in the responses, like we have in the requests from other posts? Expect way more:
Nov 1 – 30, 2018
Places API Places Details: 2389 Counts $40.61
Nov 1 – 30, 2018
Places API Contact Data: 2385 Counts $7.17
Nov 1 – 30, 2018
Places API Atmosphere Data: 2385 Counts $11.95
I do recommend to use get the Place Id like this. It would be better than call the API directly.
I stumble for this issue all day. so I hope that it would be help. who're finding the way out to get place ID from your current location.
for android
Kotlin
val mPlaceDetectionClient = Places.getPlaceDetectionClient(this.context!!)
val placeResult = mPlaceDetectionClient.getCurrentPlace(null)
placeResult.addOnCompleteListener(object : OnCompleteListener<PlaceLikelihoodBufferResponse>{
override fun onComplete(p0: Task<PlaceLikelihoodBufferResponse>) {
val likelyPlaces = p0.result
if(likelyPlaces.any()){
// get the place ID from code below
placeId = likelyPlaces[0].place.id }
}
})
or if who are implementing or developing on another language such a java. you can implement your code according to a reference below.
java
https://developers.google.com/places/android-sdk/googleapi-migration
I am developing an app where I need to calculate the distance from the current position and some other locations. I am using the GPS to access the users current location and the other locations coordinates are stored in a database. The problem occurs in the following snippet:
#Override
public void onLocationChanged(Location arg0) {
Log.v("LOCATION LAT", String.valueOf(arg0.getLatitude()));
currentLocation = arg0; //currentLocation is a global class variable
}
The problem is when I feed the DDMS with coordinates such as:
Latitude: 62.639579
Longitude: 17.909689 and log these values I get Latitude: 62.0 and Longitude 17.0 .
If I create a location object and set the lat and lng values myself it works. Like this:
#Override
public void onLocationChanged(Location arg0) {
Location current = new Location("Current location");
current.setLatitude(62.639579);
current.setLongitude(17.909689);
Log.v("Current LAT", "" + current.getLatitude());
}
EDIT SOLVED:
Found the problem. I was feeding the the DDMS with faulty formatting. Apparently this should be delimited with a comma sign, not a dot...
Have you used the permissions specified in this post? Else it kicks back to using cell tower triangulation.
Other question
Found the problem. I was feeding the the DDMS with faulty formatting. Apparently the coordinates should be delimited with a comma sign, not a dot...
you can do something like as below. Create a location variable in that you have to assign location change var
#Override
public void onLocationChanged(Location arg0) {
Location current = new Location("Current location");
current=arg0;
Log.v("Current LAT", "" + current.getLatitude());
}