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

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.

Related

Forward Geocoding with 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)
})

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;
}

FB.api post to multiple ids at same time

I'm having a little trouble here. I'm not good at javascript and all.
The problem is that I'm trying to post to some Facebook users using FB.api. However, it only works if it's only one friend at a time.
Here's my code:
FB.api({ method: 'friends.get' }, function(result) {
var user_ids="" ;
var totalFriends = result.length;
var randNo = Math.floor(Math.random() * totalFriends);
var numFriends = result ? Math.min(1,totalFriends) : 1;
if (numFriends > 0) {
for (var i=0; i<numFriends; i++) {
user_ids+= (',' + result[randNo]);
randNo ++;
if(randNo >= totalFriends){
randNo = 0;
}
}
}
FB.api(user_ids + '/feed', 'post', { message: txt2send },function(response) {
if (!response || response.error) {
alert('Error occured');
} else {
alert('Post ID: ' + response.id);
}
});
});
The output of user_ids is looking like this: ,10083461349,100082391,19293822
Hope you can help me solve this. And please don't refer me any links to help, trust me, I've tried everything.
Hope you can help me solve this. And please don't refer me any links to help, trust me, I've tried everything.
Yeah, sure. But instead of sticking to what the docs say, you’re trying to invent your own “syntax” – you really think that’s helpful …?
Accessing the Graph API generally works by making HTTP requests to /someid/someendpoint/.
But what you are trying, is to (eventually) make a request to
/,10083461349,100082391,19293822/feed
– which is just complete and utter nonsense. You just can’t access the Graph API listing multiple ids at once.
If you want to post to several user’s feeds, you have to make one API call for each one of these users.

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.

Accessing data from response of FB.api()

I am having difficulty accessing the returned JSON response data from the new Facebook JS SDK new Graph API calls.
For instance, in some of their docs where they are using the old way of using the SDK , they get a pointer to the data by response[0]
but here, it's showing that you need to use response.data[0] instead: http://developers.facebook.com/tools/console/ (click on fb.api — photo-albums)
So which is it? I know that with my code below, if I try using response[0] type of syntax to get at the returned JSON I get undefined.
If I use response[0].length I also get undefined
But if I try response.data[0].length I get 2 which I guess is the returned JSON or my 2 albums..I just don't know how to play with this returned object in terms of syntax and manipulating it, its properties, etc.
I want to in the end parse out the returned JSON using the jQuery parseJSON method but have no clue how to even pass the right syntax here for the response and just use that response object.
FB.api(uri, function(response)
{
alert("response: " + response);
// check for a valid response
if (response == "undefined" || response == null || !response || response.error)
{
alert("error occured");
return;
}
alert("response length: " + response.data.length);
}
this alert gave me 2 which makes sense. I have 2 albums.
then I tried something like response.data[0] and tried a jQuery parseJSON(response.data) or parseJSON(response.data[0]) on that and it does not work. So can someone explain the response object here as in regards to Facebook I guess? I see no docs about how to use that returned object at all and how it's constructed.
UPDATED:
Ok, so here's the entire parsing method attempt that I've stubbed out so far. I don't know if the jQuery parsing is 100% good code yet, I sort of stubbed that out but I can't even test that until I figure out how to use this response object coming back. I know it is returning JSON because I parsed another facebook response object in another method in the JS SDK so pretty sure that response[0] or response.data[0] will give you the JSON string.
function GetAllFacebookAlbums(userID, accessToken)
{
alert("inside GetAllFacebookAlbums(userID, acessToken)");
var dFacebookAlbums = {}; // dictionary
var uri = "/" + userID + "/albums?access_token=" + accessToken;
//var uri = "/me/albums";
alert("get albums uri: " + uri);
FB.api(uri, function(response)
{
alert("response: " + response);
// check for a valid response
if (response == "undefined" || response == null || !response || response.error)
{
alert("error occured");
return;
}
alert("response length: " + response.data.length);
for (var i=0, l=response.data.length; i<l; i++)
{
alert("response[key]: " + response.data[i].Name);
}
// parse JSON from response
var dJSONObjects = jQuery.parseJSON(response.data);
alert("dJSONObjects: " + dJSONObjects);
if (dJSONObjects.length == 0)
return;
// iterate through the dictionary of returned JSON objects
// and transform each to a custom facebookAlbum object
// then add each new FacebookAlbum to the final dictionary
// that will return a set of facebookAlbums
$.each(json.attributes, function () {
// add a new album to the dictionary
aFacebookAlbums[i] = FacebookAlbum(
jsonObject["id"],
jsonObject["name"],
jsonObject["location"],
jsonObject["count"],
jsonObject["link"]
);
});
});
return dFacebookAlbums;
}
It depends on the API being used. For the new Graph API single objects come back as top level object: http://graph.facebook.com/naitik -- where as collections come back with a top level data property which is an Array: http://graph.facebook.com/zuck/feed. There's also introspection to make things somewhat easier: http://developers.facebook.com/docs/api#introspection. FQL is the other popular API call, and this is where the top level response is array (think rows in SQL) which is why some examples use response[0]. Easiest thing is to just look at the response in your browser or via curl and see what it looks like.
just to clarify for all you folks who are new to FB.api (as I am) graph queries return different shaped data ... here are two examples:
FB.api('me/' function(returnData) { } ) would put the following data into returnData
{
"id": "592529630",
"name": "Hugh Abbott",
"first_name": "Hugh",
"last_name": "Abbott",
}
then if I said returnData.first_name I would get "Hugh"
If however my query was about my friends, I might run the following query
FB.api('me/friends/' function(returnData) { } )
And the shape of my data is now different:
"data": [
{
"name": "Tom Bell",
"id": "36801805"
},
{
"name": "Michael Royce",
"id": "199712888"
},
]
... so returnData is now a array ... in order to retrieve values, I would do something like the following.
returnData.data[0].name this would return "Tom Bell"
I hope this helps, as I spent a few hours wondering where I had gone wrong ... it turns out, it is all in the shape of the data !!!! good luck my friends.
Hugh
In general, the JS SDK doesn't return JSON object but it returns an object which is structured similar to the JSON Object.
Say for example : One is polling for user events data and according to the GRAPH API reference (http://developers.facebook.com/docs/reference/api/event), the returned data will have attributes as given http://developers.facebook.com/docs/reference/api/event.
The JSON object for the events data would be like this if you are using PHP SDK
Array ( [data] => Array ( [0] => Array ( [name] => sample event [start_time] => 2010-08-09T22:00:00+0000 [end_time] => 2010-08-10T01:00:00+0000 [location] => at office\ [id] => xxxxxxxx [rsvp_status] => attending )) [paging] => Array ( [previous] => hyperlink [next] => hyperlink ) )
But if you are using JS SDK, then the returned response will be like this
response.data[0...n].attributes of the particular table which you are accessing.
So, in the case of event table it will be like this :
response.data[0...n].name or response.data[0...n].id, response.data[0...n].end_time, etc
Did this ever get figured out. No one accepted anything.
alert("response[key]: " + response.data[i].Name);
The above code has Name and not name. Also, as Matti pointed out above, this works:
response.data[0].name
Just my two cents. #CoffeeAddict, accept answers to show some appreciation... Seems like someone with you rep would appreciate that. :o)
I haven't looked at the API, but I doubt FB would give you JSON encoded strings in an array. Have you tried just accessing response.data[0].someproperty?
If there is no error, then response.data should be the stuff you want (this will be an array in most cases) if you are using the new graph api. You could always just alert the JSON string if you are unsure what you are getting back.
I'm sure this must not be an issue anymore considering the Graph API explorer clearly displays the data in the form that it is returned. You are right about the difference in structure of the responses, but personally it has been useful to see what data is returned using the explorer and use the syntax accordingly.