Geo location find latitude and longitude using google API - geolocation

I am trying to retrieve the lat long for my geo location using a google api. This api accepts cell tower information. Irrespective of providing all the information I am not getting correct lat long.
https://developers.google.com/maps/documentation/geolocation/intro
Anyone used this API to find lat long? how much accuracy one should expect from the Geo location API of google?

Below I have extended this sample from google, to read Lat/Lng:
JavaScript code
function initAutocomplete() {
// Create the autocomplete object, restricting the search to geographical
// location types.
autocomplete = new google.maps.places.Autocomplete(
/** #type {!HTMLInputElement} */(document.getElementById('autocomplete')),
{types: ['geocode']});
// When the user selects an address from the dropdown, populate the address
// fields in the form.
autocomplete.addListener('place_changed', fillInAddress);
}
function fillInAddress() {
// Get the place details from the autocomplete object.
var place = autocomplete.getPlace();
// get latitude and longitude
// --------------------------
var lat = place.geometry.location.lat();
var lng = place.geometry.location.lng();
// other stuff...
}
And your address field in HTML
<input id="autocomplete" placeholder="Enter your address"
onFocus="geolocate()" type="text"></input>

Related

Determine the Barangay of a location

I have a project that requires to determine the barangay (barrio/subdivision) of a location(latitude and longitude). Is there an API out there that I can use?
In the Philippines, an address must include a Barangay. An example format of an address would be like [House No.][Street][Barangay][City][Region].
I tried to search in Google Maps API and LocationIQ API but the responses doesn't include barangays.
Unfortunately, I had not found any Maps API that provides this data. But I do found a workaround for this by getting the polygons of all barangays from geojsonph (which is in GeoJson format), then checking if the coordinates is inside that polygon using getContainers() of geojson-geometries-lookup's library.
// getBarangay.js
import GeoJsonGeometriesLookup from 'geojson-geometries-lookup'
import geoJson from 'Barangays.json'
export default function(lat, long) {
const glookup = new GeoJsonGeometriesLookup(geoJson)
const point = {type: "Point", coordinates: [long, lat]}
const containersCount = glookup.countContainers(point)
if(containersCount == 0){
// no barangays found
return null
}else{
// coordinate is inside a polygon
let result = glookup.getContainers(point, options)
return result
}
}
The getContainers(point) will check all the given polygons inside the Barangays.json that contains the point, then returns the object in geojson format.
Then, if you want to get the name of the Barangay:
let long = 120.9725526
let lat = 14.5945641
let res = getBarangay(lat, long)
console.log(res.properties.NAME_3)
However, this solution is not that optimal since you need to load the Barangay.json everytime the getBarangay() function is called, and there's 42,046 barangays in the Philippines as of now (2020). It would still be best if there's an API for this and we can just send a coordinate, and it will give back the barangay where it belongs.

How to determine region from the phone number string?

I tried using PhoneNumberKit and couldn't find any proper api which would give me the region name.
I need the region from the phone number so that I can display the appropriate flag. For example using this:
let phoneNumber = try phoneNumberKit.parse("+12563335956")
let regionCode = phoneNumberKit.countries(withCode: phoneNumber.countryCode)?.first
print("region code is: " , regionCode)
// US phone number with +1 prefix, but it prints "AG" which is wrong.
As you said, the country code can tell you which flag to use.
let phoneNumber = try phoneNumberKit.parse("+1 970162651778")
let regionCode = phoneNumberKit.getRegionCode(of: phoneNumber)
print(regionCode) // Optional("US")
You can get the country region code using the country code of the phone number.

Associate specific string to a number in google sheets

I am using a google forms to collect responses which I will then use to score people. Unfortunately some of those responses only make sense in a non numeric form, here is an example:
Q: What is your most common mode of transportation?
Car
Carpool
Public transportation
Bike
Walk
I want to be able to have google sheets automatically convert those string responses into a number, as in Car will be 20, carpool 15 and so on so that I can "grade" them and give them a score. Can this be done through google forms? Or maybe some sort of dictionary function?
Thank you!
Another method, requiring no coding, would be to make a worksheet with the encoding of the options and then use VLOOKUP to translate them.
Yep, this can be done through Google Forms. Have a look at https://developers.google.com/apps-script/reference/forms/duration-item#setPoints(Integer)
Using their code, you could go something like
var formResponses = FormApp.getActiveForm().getResponses();
// Go through each form response
for (var i = 0; i < formResponses.length; i++) {
var response = formResponses[i];
var items = FormApp.getActiveForm().getItems();
// Assume it's the first item
var item = items[0];
var itemResponse = response.getGradableResponseForItem(item);
if (itemResponse != null && itemResponse.getResponse() == 'Car') {
var points = item.asMultipleChoiceItem().getPoints();
itemResponse.setScore(points * 20);
// This saves the grade, but does not submit to Forms yet.
response.withItemGrade(itemResponse);
}
}
// Grades are actually submitted to Forms here.
FormApp.getActiveForm().submitGrades(formResponses);

How to get country specific result with Google autocomplete place api ios sdk?

I'm using below method to get autocomplete result for input string of GMSPlacesClient class:
- (void)autocompleteQuery:(NSString *)query
bounds:(GMSCoordinateBounds * GMS_NULLABLE_PTR)bounds
filter:(GMSAutocompleteFilter * GMS_NULLABLE_PTR)filter
callback:(GMSAutocompletePredictionsCallback)callback
I tried to implement bounds by multiple ways but none of them worked, I wonder if there is any standard way to get country specific results with GMSCoordinateBounds?
You can get the country specific results with the Google autocomplete place api iOS SDK. Just go to this link
let filter = GMSAutocompleteFilter()
filter.type = .Establishment
filter.country = "UK"
set the filter country to what ever the country code you want. This will then fetch only country specific results for you.
You can obtain the country codes from this link
Hope this helps.
In your google places API url, just append
&components=country:sg
here sg = country code for singapore. Append country code as per your requirement.
The country must be passed as a two character, ISO 3166-1 Alpha-2 compatible country code. you can refer Country code Of different countries
This one work for me
let placesClient = GMSPlacesClient()
let filter = GMSAutocompleteFilter()
filter.type = .Establishment
filter.country = "SG"
placesClient.autocompleteQuery(searchString, bounds: nil, filter: filter) { (results, error:NSError?) -> Void in
self.resultsArray.removeAll()
if let _ = results {
for result in results!{
if let res: GMSAutocompletePrediction = result {
// your code
}
}
}
}
in Swift 5 and later
you can custom your search by configuring the GMSAutocompleteFilter, and specify the country from its attribute country
example :
let filter = GMSAutocompleteFilter()
filter.country = "MA"
autocompleteController.autocompleteFilter = filter
the country should be a ISO 3166-1 Alpha-2 country code (case insensitive).
you can find those codes from here: Countries ISO Codes
Looks like Google autocomplete Places API for iOS doesn't support filtering by country. GMSCoordinateBounds uses the northEast and southWest bounds corresponding to the rectangular region defined by the two corners.
It might be easier to use Google Places API Web Service and filter with components=country: You can specify what country you want after country:
The full list of country codes can be found here:
https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2
Use it with:
let filter = GMSAutocompleteFilter()
filter.country = "YOURCountryCode"

Getting the street address from a google maps geocode call

I am geocoding an address using google maps API, and I need to get the street address, city, state, and zip in distinct fields. Based on the documentation of the address component types that are returned in the result, this is my code:
var address = "";
var city = "";
var state = "";
var zip = "";
geocoder.geocode( { 'address': inputAddress}, function(results, status){
if (status==google.maps.GeocoderStatus.OK){
// loop through to get address, city, state, zip
$.each(results[0].address_components, function(){
switch(this.types[0]){
case "postal_code":
zip = this.short_name;
break;
case "street_address":
address = this.short_name;
break;
case "administrative_area_level_1":
state = this.short_name;
break;
case "locality":
city = this.short_name;
break;
}
});
} else{ alert("Invalid Address"); }
});
However, it seems that when I enter addresses, "street_address" is not being returned; instead, it is returned as separate fields, most often "street_number" and "route", occasionally additional fields (such as "subpremise" for apt number). See this example of a geocoding result in the docs.
How can I get an address variable that holds any fields related to the street address? For the example in the docs, I would want "1600 Ampitheatre Parkway".
Based on the docs street_address is an address type, but that does not necessarily mean it's a type of address component - it could just be a tag used for the types array - returned with each of the objects in the results array:
The types[] array within the returned result indicates the address type. These types may also be returned within address_components[] arrays to indicate the type of the particular address component.
What you probably should be doing is traversing through your results array first and find the one that includes a street_address in the types array. Then use that object to get the formatted_address attribute (as mentioned by Aperçu). As the doc states: "the formatted_address is a string containing the human-readable address of this location". When the type is street_address, the formatted_address is equal to a street_number + route (followed by whatever other address_components are available). So you can either split(',') the formatted_address string to get the components you need - or use the address_components array of that particular object in the results array to grab the components that you need (of course doing it this way you'll need to concat the street_number and route yourself - so added logic is needed).
If you want to get all address fields in a string, use the 'formatted_address' property:
Code:
var geocoder = new google.maps.Geocoder();
var fullAdressData = '';
geocoder.geocode( { 'address': inputAddress}, function(results, status){
if (status==google.maps.GeocoderStatus.OK){
fullAdressData = results[0].formatted_address;
} else{ alert("Invalid Address"); }
});
use "route" instead of "street_address"...
case "route":
address = this.short_name;
alert(address);
break;

Resources