Forward Geocoding with Swift - swift

I am looking to be able to have a user input an address, and be able to save that address, and convert it into latitude and longitudinal coordinates. I haven't been able to find much documentation on forward geocoding, and I am having trouble starting this code. Should I ask the user to input the address by (city, state, zip code)? Or would a single address suffice? Is there a function that can do what I need? Any help is much appreciated.

I have made a simple LocationManager helper on github in which you can get the thing what you want.
There is a function getReverseGeoCodedLocation in the library. Just input your address as a String and get the complete placemark and lat, longs.
Add the LocationManager.swift file in your project
How to use it:-
LocationManager.sharedInstance.getReverseGeoCodedLocation(address: yourAddress, completionHandler: { (location:CLLocation?, placemark:CLPlacemark?, error:NSError?) in
if error != nil {
print((error?.localizedDescription)!)
return
}
if placemark == nil {
print("Location can't be fetched")
return
}
print(placemark?.addressDictionary?.description ?? "")
print((placemark?.location?.coordinate.latitude)!)
print((placemark?.location?.coordinate.longitude)!)
})
Internally it uses the geocodeAddressString of CLGeocoder
Output
Note:- It is for Swift 3.0 and above

If you want to avoid the paid Google Maps API (for commercial purposes) and usage of CLLocation you can also take a look at NominatimSwift: https://github.com/caloon/NominatimSwift
It's probably the most lightweight solution if you just want to geocode.
(Disclaimer: I made it)
NominatimSwift uses the free Nominatim API for geocoding of OpenStreetMap data. You can also search for landmarks. It requires network connectivity.
Geocoding addresses and landmarks:
Nominatim.getLocation(fromAddress: "The Royal Palace of Stockholm", completion: {(error, location) -> Void in
print("Geolocation of the Royal Palace of Stockholm:")
print("lat = " + (location?.latitude)! + " lon = " + (location?.longitude)!)
})
Reverse geocoding:
Nominatim.getLocation(fromLatitude: "55.6867243", longitude: "12.5700724", completion: {(error, location) -> Void in
print("City for geolocation 55.6867243/12.5700724:")
print(location?.city)
})

Related

Mapbox geocoding with cyrillic street names

I am trying to do geocoding with MapBox geocoding. I have a problem with searching cyrillic (Serbian) street names. When I search for city name (which are displayed latin), I can find them. Also, there is no option for MapBox to display map in Serbian language (only English, France, Germany, Spanish). However, I tried to do it with setting language to Serbian, but it doesn't help.
Here is my code, but I think there is no problem with code, it is just problem with MapBox, not offering support for Serbia.
private void getCoordinatesFromAddress(String address) {
progressDialog.setCancelable(false);
progressDialog.setMessage("Pronalazenje lokacije...");
progressDialog.show();
MapboxGeocoding mapboxGeocoding = MapboxGeocoding.builder()
.accessToken(getString(R.string.mapbox_access_token))
.query(address)
.mode(GeocodingCriteria.MODE_PLACES)
.geocodingTypes(GeocodingCriteria.TYPE_ADDRESS, GeocodingCriteria.TYPE_PLACE)
.proximity(Point.fromLngLat(21.895759,43.320902))
.country("RS")
.languages("sr")
.build();
mapboxGeocoding.enqueueCall(new Callback<GeocodingResponse>() {
#Override
public void onResponse(Call<GeocodingResponse> call, Response<GeocodingResponse> response) {
List<CarmenFeature> results = response.body().features();
if (results.size() > 0) {
progressDialog.dismiss();
Point firstResultPoint = results.get(0).center();
publicFunctions.displayToast("Lokacija " + address + " pronadjena");
move(firstResultPoint.latitude(),firstResultPoint.longitude());
} else {
publicFunctions.displayToast("Lokacija " + address + " nije pronadjena");
progressDialog.dismiss();
}
}
#Override
public void onFailure(Call<GeocodingResponse> call, Throwable throwable) {
throwable.printStackTrace();
progressDialog.dismiss();
}
});
}
Serbian is mentioned at https://docs.mapbox.com/api/search/#local-coverage
You can use the Mapbox Geocoding Playground to explore. Here's a URL that will load the playground with settings to match your geocoding query code above. Make sure you type Serbian language queries in the playground because the Serbian language filter is being applied.

Bing Maps Ajax API - get location from address

I'm using Microsoft.Maps API (AJAX control v. 7).
I want to display pin for an address.
When I use:
var loc = new Microsoft.Maps.Location(47.592, -122.332);
var pOptions = {icon: 'img/ICN_Bullet_Blue_25x38.gif', text: '1'};
var pin = new Microsoft.Maps.Pushpin(loc, pOptions);
It's working fine. How can I get latitude and longitude from address, so I will later use it for pin location ?
Bing Maps includes geocoding support (finding location by addresses).
You have two options for this:
Use the REST api directly. http://msdn.microsoft.com/en-us/library/ff701714.aspx
In that page you can find plenty of examples. You make a REST HTTP request and obtain a JSON that includes the geocoded coordinates.
Use the Microsoft.Maps.Search module. http://msdn.microsoft.com/en-us/library/hh868060.aspx
You just load the module and then do something like:
var search = new Microsoft.Maps.Search.SearchManager(map);
search.geocode({where:"some address...", count:10, callback:geocodeCallback});
and then, in your callback just handle the results:
function geocodeCallback(geocodeResult, userData)
{
var location = geocodeResult.results[0].location;
}

How to determine if address cannot be geocoded in JavaScript using MapQuest Map API

I need to geocode bunch of addresses and pin point them on the map using MapQuest. I am using
geocodeAndAddLocations
method to do that. The only problem I have is I can't figure out if geocoding for a certain address failed or not. Does anyone know how to determine that?
I have not tested this code, but according to MapQuest API, it would be something like this:
map.geocodeAndAddLocations([
{street:"555 17th St", postalCode:"80202"}
], function (response) {
if (response.results.length == 0) { // FAILED!!!
alert("can't geocode location");
} else { // SUCCESS
var location;
for (j=0; j<response.results[i].locations.length; j++) {
location = response.results[i].locations[j];
alert('lat: ' + location.latLng.lat + ', lng: ' + location.latLng.lng);
}
}
});
but again, having more of your code would give a better idea what exactly you are doing and not doing.
very simplest way...
use the following url in this jquery ajax to geocode. Even you are use mapquest
This ajax returns the json object.
$.getJSON("http://nominatim.openstreetmap.org/reverse?format=json&lat="+lat+"&lon="+lon+"", function(data) {
var loc=data.display_name;
});
append your lat and lng in the url.if unable to get the location details it throws the "unable to geocode " so you easily fix your problem.

Facebook Events appear on Google Map

is there a way I can make events on the standard Facebook events app appear on a custom Google Map I've created?
Any tips would be much appreciated.
Given you have the user_events permission, you can access the locations like so:
FB.api("/me/events", function(events) {
if(events.error)
console.error(events);
var map = "http://maps.googleapis.com/maps/api/staticmap?zoom=14&size=512x512&maptype=roadmap&sensor=false";
for(var i = 0; i < events.data.length; i++) {
var point = "&markers=color:blue%7Clabel:S%7C";
point += (events.data[i].venue.latitude + "," + events.data[i].venue.longitude);
map += point;
}
var img = document.createElement("IMG");
img.src = map;
document.body.appendChild(img);
});
I didn't test it, but this should be enough to show an example of how to access the API in the browser and render a map with it's information. This is using Google Maps static API.
I just created a python script, source here.
It queries the given facebook page and it's events and puts the data into a MySQL table. It also contains a Geo-cache library, which combines a local database with the Google Maps Geocoding API, so you can query the longitude and the latitude of the events very fast.

iphone programmatically read proxy settings

I'm looking at adding proxy support to my iphone svn client. When you set up a system wide vpn in the iphone settings you can add a global proxy. Is it possible for external apps to read this information through the api?
Apple has created a sample application for this purpose, called CFProxySupportTool.
CFProxySupportTool shows how to use the CFProxySupport APIs to determine whether a network connection should pass through a proxy; this is useful if you're not using Apple's high-level networking APIs (like CFNetwork and the Foundation URL loading system) but still want to interpret the system-supplied proxy settings.
It's currently available at
https://developer.apple.com/library/mac/#samplecode/CFProxySupportTool/Introduction/Intro.html
The code isn't exactly terse (more than 1000 lines), and is written in plain C. You can also look at the source code of ASIHTTPRequest's startRequest function, which seems to be based on CFProxySupportTool.
Here's a start:
systemProxySettings = [(NSDictionary *) CFNetworkCopySystemProxySettings() autorelease];
proxies = [(NSArray *) CFNetworkCopyProxiesForURL((CFURLRef) URL, (CFDictionaryRef) systemProxySettings) autorelease];
if (!proxies.count)
return;
firstProxySettings = [proxies objectAtIndex:0];
if (nil != (pacScriptURL = [firstProxySettings objectForKey:(NSString *)kCFProxyAutoConfigurationURLKey]))
{
CFErrorRef cfErrorRef = NULL;
NSError *nsError = nil;
NSString *script;
script = [NSString stringWithContentsOfURL:pacScriptURL
usedEncoding:NULL
error:&nsError];
if (nsError)
return;
proxies = [(NSArray *) CFNetworkCopyProxiesForAutoConfigurationScript((CFStringRef) script, (CFURLRef) URL, &cfErrorRef) autorelease];
if (cfErrorRef || !proxies.count)
return;
firstProxySettings = [proxies objectAtIndex:0];
}
/* Now use `firstProxySettings' */
A Swift 4 version (special thanks to mortehu for providing the initial example).
//Shown this way for clarity, you may not want to waste cycles in your production code
if let url = URL(string: "https://someurloutthere.com") {
let systemProxySettings = CFNetworkCopySystemProxySettings()?.takeUnretainedValue() ?? [:] as CFDictionary
let proxiesForTargetUrl = CFNetworkCopyProxiesForURL(url as CFURL, systemProxySettings).takeUnretainedValue() as? [[AnyHashable: Any]] ?? []
for proxy in proxiesForTargetUrl {
print("Proxy: \(String(describing: proxy))")
//Print the proxy type
print("Proxy Type: \(String(describing: proxy[kCFProxyTypeKey]))")
//There different proxy value keys depending on the type, this is an example of getting the proxy config script if the type is kCFProxyTypeAutoConfigurationURL. If the proxy type were kCFProxyTypeSOCKS you would want to access the SOCKS property keys to see/get the SOCKS proxy values
print("Proxy Autoconfig script URL: \(String(describing: proxy[kCFProxyAutoConfigurationURLKey]))"
}
}
Have you investigated using something like ASIHttpRequest, see the section in the how to document describing proxy support.
At the very least the source code should contain some helpful guidance.
Take a look at the CFProxySupport API, in particular CFNetworkCopyProxiesForURL() will let you read the proxies that are needed to get to a particular URL.