Bing Maps Ajax API - get location from address - bing-maps

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

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

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.

How to connect asp.net web server to iPhone

I realize that there are other posts asking similar questions, but do not quite answer the question I have. I apologize if this is not enough info, formatting is off, or whatnot. Its my first time posting.
Basically my group is doing an iPhone app that needs to interface with our sql server database. But because they can't talk directly with eachother we are implementing an asp.net medium that will accept XML and apparently will need to output JSOD. Currently I have a .asmx written with "working" code (test string inside code). Right now I am just trying to accept the XML from the iPhone. I feel like we are missing something either on his end (iPhone) or my end (.asmx). Hopefully you bright minds out there can fill me in because with our combined research....i feel theres something missing. Maybe im wrong and Ive we've got our stuff together which would be awesome.
apparently this is all he needs (according to his research) on his end in order to connect and transfer the information. obviously its not .asmx but it shouldn't matter the extension right?
NSURL *url = [NSURL URLWithString:#"http://myurl.com/RequestHandler.ashx"];
Here is the code that I have with my .asmx (note the function is where the meat is at)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Xml.Linq;
namespace Outbreak_Mobile
{
[WebService(Namespace = "http://OutbreakMobile.net/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class Service1 : System.Web.Services.WebService
{
[WebMethod (Description="To intake an xml package from iPhone and store it")]
public string iPhoneLocation(string xml)
{
//test string to output to screen
string location = null;
//test string of xml to be parsed
//will be converting next line to parse input xml
//string xml = #"<Player>
// <Latitude>42.13245465</Latitude>
// <Longitude>11.11111111</Longitude>
// </Player>";
//line to parse document
//xdocument doc = xdocument.parse(incoming xml)
XDocument doc = XDocument.Parse(xml);
//grabs the information inside <player> tags
XElement loc = doc.Elements("Player").SingleOrDefault();
if (loc != null)
{
var lat = (double)loc.Element("Latitude");
var lng = (double)loc.Element("Longitude");
location = "Lat: " + lat + '\n' + "Long: " + lng;
}
//this is what puts out to the screen
return location;
}
}
}
currently the output of the string 'location' was just for functionality testing and will change when I know that I am receiving the packages correctly. What are we missing in order to connect with one another?
Thank you all in advance!
You created a NSURL object. Now you need to create a NSURLConnection to download the data from that URL.
http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/URLLoadingSystem/Tasks/UsingNSURLConnection.html
And to transfer the NSData object you got from the connection just use NSString -initWithData:encoding: method.

How to construct a REST API that takes an array of id's for the resources

I am building a REST API for my project. The API for getting a given user's INFO is:
api.com/users/[USER-ID]
I would like to also allow the client to pass in a list of user IDs. How can I construct the API so that it is RESTful and takes in a list of user ID's?
If you are passing all your parameters on the URL, then probably comma separated values would be the best choice. Then you would have an URL template like the following:
api.com/users?id=id1,id2,id3,id4,id5
api.com/users?id=id1,id2,id3,id4,id5
api.com/users?ids[]=id1&ids[]=id2&ids[]=id3&ids[]=id4&ids[]=id5
IMO, above calls does not looks RESTful, however these are quick and efficient workaround (y). But length of the URL is limited by webserver, eg tomcat.
RESTful attempt:
POST http://example.com/api/batchtask
[
{
method : "GET",
headers : [..],
url : "/users/id1"
},
{
method : "GET",
headers : [..],
url : "/users/id2"
}
]
Server will reply URI of newly created batchtask resource.
201 Created
Location: "http://example.com/api/batchtask/1254"
Now client can fetch batch response or task progress by polling
GET http://example.com/api/batchtask/1254
This is how others attempted to solve this issue:
Google Drive
Facebook
Microsoft
Subbu Allamaraju
I find another way of doing the same thing by using #PathParam. Here is the code sample.
#GET
#Path("data/xml/{Ids}")
#Produces("application/xml")
public Object getData(#PathParam("zrssIds") String Ids)
{
System.out.println("zrssIds = " + Ids);
//Here you need to use String tokenizer to make the array from the string.
}
Call the service by using following url.
http://localhost:8080/MyServices/resources/cm/data/xml/12,13,56,76
where
http://localhost:8080/[War File Name]/[Servlet Mapping]/[Class Path]/data/xml/12,13,56,76
As much as I prefer this approach:-
api.com/users?id=id1,id2,id3,id4,id5
The correct way is
api.com/users?ids[]=id1&ids[]=id2&ids[]=id3&ids[]=id4&ids[]=id5
or
api.com/users?ids=id1&ids=id2&ids=id3&ids=id4&ids=id5
This is how rack does it. This is how php does it. This is how node does it as well...
There seems to be a few ways to achieve this. I'd like to offer how I solve it:
GET /users/<id>[,id,...]
It does have limitation on the amount of ids that can be specified because of URI-length limits - which I find a good thing as to avoid abuse of the endpoint.
I prefer to use path parameters for IDs and keep querystring params dedicated to filters. It maintains RESTful-ness by ensuring the document responding at the URI can still be considered a resource and could still be cached (although there are some hoops to jump to cache it effectively).
I'm interested in comments in my hunt for the ideal solution to this form :)
You can build a Rest API or a restful project using ASP.NET MVC and return data as a JSON.
An example controller function would be:
public JsonpResult GetUsers(string userIds)
{
var values = JsonConvert.DeserializeObject<List<int>>(userIds);
var users = _userRepository.GetAllUsersByIds(userIds);
var collection = users.Select(user => new { id = user.Id, fullname = user.FirstName +" "+ user.LastName });
var result = new { users = collection };
return this.Jsonp(result);
}
public IQueryable<User> GetAllUsersByIds(List<int> ids)
{
return _db.Users.Where(c=> ids.Contains(c.Id));
}
Then you just call the GetUsers function via a regular AJAX function supplying the array of Ids(in this case I am using jQuery stringify to send the array as string and dematerialize it back in the controller but you can just send the array of ints and receive it as an array of int's in the controller). I've build an entire Restful API using ASP.NET MVC that returns the data as cross domain json and that can be used from any app. That of course if you can use ASP.NET MVC.
function GetUsers()
{
var link = '<%= ResolveUrl("~")%>users?callback=?';
var userIds = [];
$('#multiselect :selected').each(function (i, selected) {
userIds[i] = $(selected).val();
});
$.ajax({
url: link,
traditional: true,
data: { 'userIds': JSON.stringify(userIds) },
dataType: "jsonp",
jsonpCallback: "refreshUsers"
});
}