Perform a Google/Bing Maps search from a utr - c#

I'm working on project that simulates (for lack of better word) a GPS. The user is able to select a State, City and address e.g 000 someadress.dr and I have it set up so that when the submit button is clicked all of these components are combined into a single string. I'm wondering if its possible to perform a map search on either platform through the address bar, if it is could possibly do something like this:
private void btnSubmitAddress_Click(object sender, EventArgs e) {
string stateSelected = this.cbState.Text; // Stores the selected State
string citySelected = this.cbCity.Text; // Stores the selected City
string addressSelected = this.cbPreDefAddress.Text; // Store the selected address
string result = addressSelected + " " + citySelected + " " + stateSelected; // Creates a single address string.
wbSatNavBrowser.Navigate("https://www.bing.com/maps/search?" + result);
}

The Bing Maps website is a consumer product and shouldn't be loaded inside of business applications. Instead, consider using the Bing Maps developer API's. The Bing Maps WPF control works inside of WinForms, here is a blog post on this: https://rbrundritt.wordpress.com/2012/01/05/using-bing-maps-in-winforms/
You can geocode locations using the REST services. Here is a great .NET library for using these services: https://github.com/Microsoft/BingMapsRESTToolkit
If you want the most mapping features, you can also host the Bing Maps web control inside of a web browser control. Here is a code sample: https://code.msdn.microsoft.com/Using-the-Bing-Maps-V8-Web-07e21f3a?redir=0

The docs show some examples of how to pass parameters.
This example sets the centerpoint of the map.
http://bing.com/maps/default.aspx?cp=47.677797~-122.122013
To open Bing Maps to a specific address:
http://bing.com/maps/default.aspx?rtp=adr.One%20Microsoft%20Way,%20Redmond,%20WA%2098052~pos.45.23423_-122.1232_MyPlace&rtop=0~1~0

Related

Is it possible to place Bing/Google Maps autocomplete postal address textbox in desktop windows form app using C#?

I'm a noob at C#, this is my first programming language and I am currently working my way through the book C# in a Nutshell. I have started a project to automate a lot of what I do at work all day.
If it is possible can anyone recommend a good place to start researching how to do this specifically? The only resource that I can find is:
Google maps autocomplete textbox in c#
But he says in the end he could never get it to work. It gives me an idea about how to go about it but I don't know what he was doing wrong.
I want to implement an order placing system and the first thing the user will need to do is enter customer name and address.
The end game is getting the address and comparing it to a database of stored addresses, if the post/zip code matches then load up the account and if it doesn't then create a new account using the address details.
Being able to use a Microsoft or Google api would prevent me from having to host a database with every UK address in it.
EDIT: https://developers.google.com/maps/documentation/javascript/examples/places-autocomplete-addressform
As per Google, below is the JavaScript code for this functionality but in a web page. As you can see the comments state that the JS library Places is required. Does this mean I can't just work on the conversion and that some functionality will be missing. This is all embedded within HTML which I have not included:
// This example displays an address form, using the autocomplete feature
// of the Google Places API to help users fill in the information.
// This example requires the Places library. Include the libraries=places
// parameter when you first load the API. For example:
// <script src="https://maps.googleapis.com/maps/api/js? key=YOUR_API_KEY&libraries=places">
var placeSearch, autocomplete;
var componentForm = {
street_number: 'short_name',
route: 'long_name',
locality: 'long_name',
administrative_area_level_1: 'short_name',
country: 'long_name',
postal_code: 'short_name'
};
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();
for (var component in componentForm) {
document.getElementById(component).value = '';
document.getElementById(component).disabled = false;
}
// Get each component of the address from the place details
// and fill the corresponding field on the form.
for (var i = 0; i < place.address_components.length; i++) {
var addressType = place.address_components[i].types[0];
if (componentForm[addressType]) {
var val = place.address_components[i][componentForm[addressType]];
document.getElementById(addressType).value = val;
}
}
}
// Bias the autocomplete object to the user's geographical location,
// as supplied by the browser's 'navigator.geolocation' object.
function geolocate() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var geolocation = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
var circle = new google.maps.Circle({
center: geolocation,
radius: position.coords.accuracy
});
autocomplete.setBounds(circle.getBounds());
});
}
}
Bing Maps only provides auto suggest/complete through their web control currently. You can host this inside of a web browser control in your app but that will be messy and likely won't work well with your layout.
Take a look at Azure Location Based Serv- ices. They have several REST services which can be used for auto suggest/complete for addresses/places, points of interest and more. Simply set the typeahead URL parameter to true to put the service into predictive mode. Here are some useful resources:
https://learn.microsoft.com/en-us/azure/location-based-services/tutorial-search-location
https://learn.microsoft.com/en-us/rest/api/location-based-services/search/getsearchaddress
https://learn.microsoft.com/en-us/rest/api/location-based-services/search/getsearchfuzzy
https://learn.microsoft.com/en-us/rest/api/location-based-services/search/getsearchpoi
https://learn.microsoft.com/en-us/rest/api/location-based-services/search/getsearchpoicategory

How to get Bing Map Session Key from code behind

To reduce the billable transaction in my web form asp.net project, i decided to test it.
I have come across following example on msdn for session key.
Map.CredentialsProvider.GetCredentials(
Function(c)
Dim sessionKey As String = c.ApplicationId
'Generate a request URL for the Bing Maps REST services.
'Use the session key in the request as the Bing Maps key
Return 0
End Function)
My Code example
private String GeocodeAddress(string address)
{ string results = "";
string key = "Bing Maps key";
GeocodeRequest geocodeRequest = new GeocodeRequest();
// Set the credentials using a valid Bing Maps key
geocodeRequest.Credentials = new GeocodeService.Credentials();
geocodeRequest.Credentials.ApplicationId = key;
// Set the full address query
geocodeRequest.Query = address;
// Set the options to only return high confidence results
ConfidenceFilter[] filters = new ConfidenceFilter[1];
filters[0] = new ConfidenceFilter();
filters[0].MinimumConfidence = GeocodeService.Confidence.High;
// Add the filters to the options
GeocodeOptions geocodeOptions = new GeocodeOptions();
geocodeOptions.Filters = filters;
geocodeRequest.Options = geocodeOptions;
// Make the geocode request
GeocodeServiceClient geocodeService = new GeocodeServiceClient();
GeocodeResponse geocodeResponse = geocodeService.Geocode(geocodeRequest);
if (geocodeResponse.Results.Length > 0)
results = String.Format("Latitude: {0}\nLongitude: {1}",
geocodeResponse.Results[0].Locations[0].Latitude,
geocodeResponse.Results[0].Locations[0].Longitude);
else
results = "No Results Found";
return results;
}
After debugging it, i can't see any difference b/w (application id / session key) and Bing Api key. How can i get sessionkey in above example?
The session key can only be used on the same page as the interactive map. Passing a session key between pages is not allowed. Assuming that you have an AJAX button or something that is processing some code on the server and returning it to the same page as the map, then this would be alright.
The first bit of code looks like you are trying to generate a session key in .NET. This would only be possible if you where using Silverlight or WPF. I'll assume you are not using the Bing Maps WPF control on the server as that's really against the terms of use. If you are using Silverlight, then there is no need to pass a key to the server side.
So lets assuming you generate a key in JavaScript from the Bing Maps v7 control and pass it to AJAX button handler on the server. If this is the case then it's alright.
In your code it looks like you are using the really old legacy SOAP services which is not recommended. In fact I stopped recommending them about 4 or 5 years ago. The documentation was taken offline a couple of years ago. You should be using the Bing Maps REST services which are faster, more accurate and has more features. You can find documentation on how to use them in .NET here: http://msdn.microsoft.com/en-us/library/jj819168.aspx
Also, here are some tips on using the REST services: http://blogs.bing.com/maps/2013/02/14/bing-maps-rest-service-tips-tricks/
ApplicationId and session key are the same thing. The SOAP services are so old it used to have a different name.
You won't see any differences in the reports right away. It can take up to a week for the reports to sync up across all the servers/data centers as it's a low priority job with massive amounts of data.
If your application has decent traffic you will likely end up with a lot more non-billable transactions than billable transactions which will likely cause your account to be flagged and investigated and possibly blocked.
What you should be doing is geocoding your addresses ahead of time and storing the coordinates. This is how most applications handle this type of scenario. The only time you should need to geocode on the fly is if you have a search box for user input, all everything else should be geocoded ahead of time for performance.

how to get country name from latitude and longitude

How can i get the country name from latitude and longtitude using c#?
Im using the Bing.Map API
Location location12 = new Location(location.Latitude, location.Longitude);
MapLayer.SetPosition(pin, location12);
Map.Children.Add(pin);
string placeName = GetPlaceNameForCoordinates(location.Latitude, location.Longitude);
You'll want to use a reverse geocoding API of some kind. For example:
The Bing Maps API (the webservice)
The Google Geocoding API
The Geonames API
If you're already using the Bing.Maps SDK, you should use the Map.SearchManager property to get a SearchManager, and then use the ReverseGeocodeAsync method. In particular, as noted in comments, mixing and matching which API you use to show data via other SDKs may well violate the terms and conditions of both: be careful which technologies you use within a single application. (Even though this question gives sample code using the Bing Maps SDK, I've kept the list above in order to help others who may come with a slightly different context.)
For example:
var manager = map.SearchManager;
var request = new ReverseGeocodeRequestOptions(location) {
IncludeEntityTypeFlags = ReverseGeocodeEntityType.CountryRegion
};
var response = await manager.ReverseGeocodeAsync(
new ReverseGeocodeRequestOptions(location) { );
// Use the response
If you decide to use the Geonames API, the data can be downloaded for offline use too.
I've created a github project with sample code that does this without api calls
see here
Very simple country name and id returned

calling another http request upon changing page

I'm working with windows phone apps and I'm using here rest places api for my data and i retrieving data as json that give me information about location nearby like this
position: [ 37.77704 , -122.39494 ]
distance: 1241
title: Caltrain-San Francisco
averageRating: 0.0
category: { Public transport }
icon: http://download.vcdn.nokia.com/p/d/places2/icons/categories/11.icon
vicinity: 700 4th St<br/>San Francisco, CA 94107
having: [ ]
type: urn:nlp-types:place
href: http://demo.places.nlp.nokia.com/places/v1/places/8409q8yy-a7395cccbfc4474ba469f3ddc03e041b;context=Zmxvdy1pZD00OWQxZDY0Zi0zODc5LTVlNDAtOWY4ZC04ZGFmNWMyMGZhZDFfMTM4OTg4NDQxMzUxNV8wXzM1MjkmcmFuaz0w?app_id=lp3VaO8uhOFe0akZ4J1m&app_code=JwL7MNaSarML92oqEDshAg
id: 8409q8yy-a7395cccbfc4474ba469f3ddc03e041b
and i notice that if i open
href: http://demo.places.nlp.nokia.com/places/v1/places/8409q8yy-a7395cccbfc4474ba469f3ddc03e041b;context=Zmxvdy1pZD00OWQxZDY0Zi0zODc5LTVlNDAtOWY4ZC04ZGFmNWMyMGZhZDFfMTM4OTg4NDQxMzUxNV8wXzM1MjkmcmFuaz0w?app_id=lp3VaO8uhOFe0akZ4J1m&app_code=JwL7MNaSarML92oqEDshAg
i will go into other page that contain much detailed information about that location, so how can i get all of this data?the general and detailed data from that href
method that i using to get general data is using this
WebClient client = new WebClient();
Uri uri = new Uri(transportURL1 + latitude + "%2C" + longitude + transportURL2, UriKind.Absolute);
client.DownloadStringCompleted += (s, e) =>
{
if (e.Error == null)
{
RootObject result = JsonConvert.DeserializeObject<RootObject>(e.Result);
hereRestProperty = new ObservableCollection<Item>(result.results.items);
}
else
{
MessageBox.Show(e.Error.ToString());
}
};
client.DownloadStringAsync(uri);
so my app scenario is mainpage showing general location data and when I tap one of the location data it will navigate to detailpage that contain information from that href
how to do that?
edit: my work around is getting href and using that href to calling http request but i have no idea how to do all that...
edit2: after looking around I come up with idea of having mainpage with list of general information and if I click into one of the item in list it will navigate me to detailpage that will request from that href but i just don't know how to execute that in mvvm aproach...
If it is safe to assume that you are trying to add value to your app by adding a places feature, I would suggest that for Windows Phone 8 you would be better off launching HERE Maps directly using the HERE Maps Launchers API
For example, if your app is about hiking trails it would make sense to add a feature for finding details of places to eat or stay near that hiking trail - but you wouldn't need to create your own code to request, format and display the in-depth places data, just fire up the Maps app already on the device (passing in the href from the initial REST request if necessary). The advantage of doing this is threefold, firstly you can add this feature in four lines of code, secondly the user is presented with the places information in a familiar format, and finally information is retrieved from the device itself which alleviates the need to make additional HTTP requests.
One or more of the following tasks may be useful:
ExploremapsShowPlaceTask allows you to start the Maps application with the map centered to a place shown in the map.
ExploremapsSearchPlacesTask allows you to start the Maps application with the search view.
ExploremapsExplorePlacesTask allows you to start the Maps application where the nearby places of interest are shown.
PlacesShowDetailsByLocationTask allows you to start the Maps application with the places view for the selected place.
PlacesShowDetailsByIdHrefTask allows you to start the Maps application with the places view for the selected place.
Note that if HERE Maps is not installed on the Windows Phone 8 device, the user will be directed to download it for free from the app store.

Get location name by giving ZIP codes

I need to display the location and city name when a user enters a ZIP Code. How do I get the corresponding location names?
I would use a website like
http://www.zipinfo.com/search/zipcode.htm
and just send the zipcode to that, retrieve the input, parse for the city name, easy as that.
Try the USPS zipcode API - http://www.usps.com/webtools/welcome.htm
You can use the PlaceFinder geocoding web service to make REST based requests using the postal code you want to resolve to a name. The service supports both XML and JSON response formats. Here is a listing of the response elements returned by the service.
Using .NET, you would leverage the client or request/response classes in the System.Net namespace to make a request to the service and process the reponse.
The simplest way would be to use strings. You could alternatively create a ZIP class, if you wanted to get fancy.
using System;
using System.Collections.Generic;
class Program
{
// declare your variable
private static Dictionary<string, string> zipLookup;
public static void CreateZips()
{
zipLookup = new Dictionary<string, string>();
zipLookup.Add("90210", "Beverly Hills");
// fill all other values, probably from a db
}
static void Main(string[] args)
{
CreateZips();
var test = "90210";
if (zipLookup.ContainsKey(test))
{
Console.WriteLine(test.ToString() + "=" + zipLookup[test]);
}
else
{
Console.WriteLine(test.ToString() + " location unknown");
}
}
}
For more details on ZIPs, check out Wikipedia
I work in the address verification industry for a company called SmartyStreets. The solutions presented here are all functional in a variety of ways, but beware of their limitations and specialties. For example, Yahoo's service is more like address suggestion, not validation. The USPS web service is quite limited in the results it returns, for example: you won't get the County and Component data of an address, actual deliverability, etc.
For a more flexible, free solution -- may I suggest our LiveAddress API? It's a REST-ful endpoint which, given a street address (for example) and ZIP code, will fully and accurately complete the entire address.
Alternatively, you can use https://thezipcodes.com/
This has almost all the data that I used for the search.
Use http://thezipcodes.com/docs to use the API.

Categories

Resources