skip to main | skip to sidebar

Java Programs and Examples with Output

Pages

  • Home
 
  • RSS
  • Twitter
Showing posts with label Bing API Example. Show all posts
Showing posts with label Bing API Example. Show all posts
Thursday, October 18, 2012

Reverse Geocoding Using Bing Rest Api

Posted by Raju Gupta at 12:00 AM – 0 comments
 
For the past several years, the Bing Map API has made search data available for developers to innovate and build various address/ geocode related applications. Using Bing Map API developer can retrieve latitude & longitude (geocode) of an address/ zipCode which is called Geocoding. Vice versa, developer can get address/ zipCode from latitude & longitude (geocode) which is called reverse geocoding.

  1. In this approach I invoked http://dev.virtualearth.net/REST/v1/Locations Bing Api. In order to invoke this API developer needs an authentication key by purchasing a license. There are several other similar apis available in Bing which differ by different parameters.
  2. To get a license for using the Geocoding Webservice, developer needs to register for Bing Maps Developer account. Developer can sign up here: http://www.microsoft.com/maps/product/licensing.aspx . Developer also can use a free version of api without any license fee [free version of api has some limitation which is also documented in the above link]
  3. Now, I am assuming developer will have their own Bing Map authentication key. For this documentation and example I am using an authentication key value: "XXXXXXX".
  4. Create a class ReverseGeoCodeFetcher that would hold all the logic for interacting with reverse geocoding webservices. By following the logic developer can create their own functionality by enhancing the logic.
  5. In ReverseGeoCodeFetcher class I hardcode "latitude", "longitude", "resposeOutputType" value inside main() method. Developer needs to modify all this dynamic value based on their requirement.
  6. I passed "latitude", "longitude", "resposeOutputType" as a parameter to prepareDynamicURL() function to prepare the URL dynamically by appending the parameter after the Bing Map API URL.
  7. After preparing the URL dynamically, I invoked getResultHttpAsStream() method. This method opens calls the Bing URL by opening HttpURLConnection. After receiving a success status code from Bing API, this method populates the response data in a string and return the data to main() method for displaying. In this example I didn't play with result further and just displayed the data using SOP. But developer needs to process the result based on requirement.
  8. In this example, Bing API will return the data in XML format. Bing currently returns the data in XML/ JSON format. Developer can decide the response format type by "output" parameter value "xml/json". In this example "output" parameter value "xml" has been used by passing the "resposeOutputType" value as "xml".





import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import org.apache.commons.lang.StringUtils;



public class ReverseGeocodeFetcher {
 //Bing service REST-URL
 public static final String bingLocationUrl="http://dev.virtualearth.net/REST/v1/Locations";
 //Authentication key to invoke Bing URL [user need to change this key]
 public static final String bingAuthenticationKey="API Key";
 
 protected static final String EQUAL = "=";
 protected static final String AND = "&";
 protected static final String PARAM_KEY = "key";
 protected static final String PARAM_OUTPUT = "output";

 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  ReverseGeocodeFetcher reverseGeocodeFetcher = new ReverseGeocodeFetcher();
  String latitude = "42.399851";
  String longitude = "-71.259792";
  String resposeOutputType = "xml";  
  /*
   * invoking prepareDynamicURL() to prepare URL dynamically by appending 
   * latitude, longitude
   */
  String dynamicURl = reverseGeocodeFetcher.prepareDynamicURL(latitude, longitude, resposeOutputType);
  System.out.println("dynamicURl: " + dynamicURl);
  String result = null;
  if(!StringUtils.isEmpty(dynamicURl)){
   result = reverseGeocodeFetcher.getResultHttpAsStream(dynamicURl);
  }
  System.out.println("result: " + result);
 }
 
 /*
  * This prepareDynamicURL() prepare URL dynamically by appending 
  * street latitude, longitude  as parameter 
  * after the static part of Bing api
  */
 protected String prepareDynamicURL(String latitude, String longitude, 
    String resposeOutputType ) 
 {
  double x= (Double.valueOf(latitude)).doubleValue();
  double tempLatitude = ((Double.valueOf(latitude)).doubleValue());
  double tempLongitude = ((Double.valueOf(longitude)).doubleValue());
  StringBuffer sb = new StringBuffer();
  sb.append(bingLocationUrl).append("/").append(tempLatitude).append(",").append(tempLongitude).append("?");
  //appending bing authentication key
  sb.append(PARAM_KEY).append(EQUAL).append(bingAuthenticationKey).append(AND);
  /*
   * appending response type/ output type value. Bing return response in
   * XML/ JSON/ Text format.   
  */
  sb.append(PARAM_OUTPUT).append(EQUAL).append(resposeOutputType);

  return sb.toString();
 }
 
 /*
  * this getResultHttpAsStream() used to invoke Bing Rest-api
  * using  HttpURLConnection and converting the result in string format
  */
 protected final String getResultHttpAsStream(String url) 
 {
  System.out.println("url = " + url);
     HttpURLConnection conn = null;
     InputStream in = null;
     BufferedReader rd = null;
     StringBuffer sb = new StringBuffer();
  try {
   URL u = new URL(url);
   conn = (HttpURLConnection)u.openConnection();
   
   if(conn.getResponseCode() == HttpURLConnection.HTTP_OK){
    //in = conn.getInputStream();
    // Get the response
    rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String line;
    while ((line = rd.readLine()) != null)
    {
     sb.append(line);
    }
    rd.close();
   } 
   
  } catch (Throwable e) {
   in = null;
  } finally{
   conn = null;
  }
  return sb.toString();
 }
}


[ Read More ]
Read more...
Wednesday, October 17, 2012

Geocoding Using Bing Rest Api

Posted by Raju Gupta at 9:00 PM – 0 comments
 
For the past several years, the Bing Map API has made search data available for developers to innovate and build various address/ geocode related applications. Using Bing Map API developer can retrieve latitude & longitude (geocode) of an address/ zipCode which is called Geocoding.


In this documentation, I mainly focused to show the approach for Geocoding using Bing Map Rest Api from a standalone sample Java class example. Below I am giving an overview of what / how I approached with doing that:

  1. In this approach I invoked http://dev.virtualearth.net/REST/v1/Locations Bing Api. In order to invoke this API developer needs an authentication key by purchasing a license. There are several other similar apis available in Bing which differ by different parameters.
  2. To get a license for using the Geocoding Webservice, developer needs to register for Bing Maps Developer account. Developer can sign up here: http://www.microsoft.com/maps/product/licensing.aspx . Developer also can use a free version of api without any license fee [free version of api has some limitation which is also documented in the above link]
  3. Now, I am assuming developer will have their own Bing Map authentication key. For this documentation and example I am using an authentication key value: "XXXXXXX".
  4. Create a class GeoCodeFetcher that would hold all the logic for interacting with geocoding webservices. By following the logic developer can create their own functionality by enhancing the logic.
  5. In GeoCodeFetcher class I hardcode "streetAddress", "city", "state", "country", "zipCode", "resposeOutputType" value inside main() method. Developer needs to modify all this dynamic value based on their requirement.
  6. I passed "streetAddress", "city", "state", "country", "zipCode", "resposeOutputType" as a parameter to prepareDynamicURL() function to prepare the URL dynamically by appending the parameter after the Bing Map API URL. Inside this prepareDynamicURL() function, I also called another encodeString() function to encode the value of parameters: streetAddress, city, state, country, zipCode.
  7. After preparing the URL dynamically, I invoked getResultHttpAsStream() method. This method opens calls the Bing URL by opening HttpURLConnection. After receiving a success status code from Bing API, this method populates the response data in a string and return the data to main() method for displaying. In this example I didn't play with result further and just displayed the data using SOP. But developer needs to process the result based on requirement.
  8. In this example, Bing API will return the data in XML format. Bing currently returns the data in XML/ JSON format. Developer can decide the response format type by "output" parameter value "xml/json". In this example "output" parameter value "xml" has been used by passing the "responseOutputType" value as "xml".


For the rest, I have written commented code for your reading, this should be fairly self-explanatory.



import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import org.apache.commons.lang.StringUtils;



public class GeocodeFetcher {
 //Bing service REST-URL
 public static final String bingLocationUrl="http://dev.virtualearth.net/REST/v1/Locations";
 //Authentication key to invoke Bing URL [user need to change this key]
 public static final String bingAuthenticationKey=" XXXXXXX";
 
 protected static final String EQUAL = "=";
 protected static final String AND = "&";
 private static final String PARAM_COUNTRY = "countryRegion";
 private static final String PARAM_STATE = "adminDistrict";
 private static final String PARAM_CITY = "locality";
 private static final String PARAM_ZIP = "postalCode";
 private static final String PARAM_ADDRESS = "addressLine";
 protected static final String PARAM_KEY = "key";
 protected static final String PARAM_OUTPUT = "output";

 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  GeocodeFetcher geocodeFetcherInstance = new GeocodeFetcher();
  String streetAdreess = "3301 Stearns Hill Rd";
  String city = "Waltham";
  String state = "MA";
  String country = "US";
  String zipCode = "02451";
  String resposeOutputType = "xml";  
  /*
   * invoking prepareDynamicURL() to prepare URL dynamically by appenidng 
   * street address, city, state, country and zipCode
   */
  String dynamicURl = geocodeFetcherInstance.prepareDynamicURL(streetAdreess, city, state, zipCode, country, resposeOutputType );
  System.out.println("dynamicURl: " + dynamicURl);
  String result = null;
  if(!StringUtils.isEmpty(dynamicURl)){
   result = geocodeFetcherInstance.getResultHttpAsStream(dynamicURl);
  }
  System.out.println("result: " + result);
 }
 
 /*
  * This prepareDynamicURL() prepare URL dynamically by appending 
  * street address, city, state, country and zipCode as parameter 
  * after the static part of Bing api
  */
 protected String prepareDynamicURL(String streetAdreess, String city, 
   String state, String zipCode, String country, String resposeOutputType ) 
 {
  StringBuffer sb = new StringBuffer();
  sb.append(bingLocationUrl).append("?");
  sb.append(PARAM_COUNTRY).append(EQUAL).append(country).append(AND);
  try {
   sb.append(PARAM_STATE).append(EQUAL).append(encodeString(state)).append(AND);
  } catch (UnsupportedEncodingException e) {
   System.out.println("Unsupported code of state. Ignore the state");
  }
  try {
   sb.append(PARAM_CITY).append(EQUAL).append(encodeString(city)).append(AND);
  } catch (UnsupportedEncodingException e) {
   System.out.println("Unsupported code of city. Ignore the city");
  }
  sb.append(PARAM_ZIP).append(EQUAL).append(zipCode).append(AND);
  try {
   sb.append(PARAM_ADDRESS).append(EQUAL).append(encodeString(streetAdreess)).append(AND);
  } catch (UnsupportedEncodingException e) {
   System.out.println("Unsupported code of street. Ignore the address line");
  }
  //appending bing authentication key
  sb.append(PARAM_KEY).append(EQUAL).append(bingAuthenticationKey).append(AND);
  
  /*
   * appending response type/ output type value. Bing return response in
   * XML/ JSON/ Text format.   
  */
  sb.append(PARAM_OUTPUT).append(EQUAL).append(resposeOutputType);
  return sb.toString();
 }
 
 /*
  * this encodeString() used to encode 
  * street address, city, state, country and zipCode
  */
 protected String encodeString(String str) 
 throws UnsupportedEncodingException
 {
  return URLEncoder.encode(str.replace(".", "").replace(",","").replace(":", ""), "UTF-8");//.replace("+", "%20");
 }
 
 /*
  * this getResultHttpAsStream() used to invoke Bing Rest-api
  * using  HttpURLConnection and converting the result in string format
  */
 protected final String getResultHttpAsStream(String url) 
 {
  System.out.println("url = " + url);
     HttpURLConnection conn = null;
     InputStream in = null;
     BufferedReader rd = null;
     StringBuffer sb = new StringBuffer();
  try {
   URL u = new URL(url);
   conn = (HttpURLConnection)u.openConnection();
   
   if(conn.getResponseCode() == HttpURLConnection.HTTP_OK){
    //in = conn.getInputStream();
    // Get the response
    rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String line;
    while ((line = rd.readLine()) != null)
    {
     sb.append(line);
    }
    rd.close();
   } 
   
  } catch (Throwable e) {
   in = null;
  } finally{
   conn = null;
  }
  return sb.toString();
 }

[ Read More ]
Read more...
Older Posts
Subscribe to: Posts ( Atom )

List of Java Programs

  • Java Program to check Greater between the Two Number
  • Java Program to find that given number is Palindrome or not
  • Java Program to Demonstrate the Use of Pre and Post Operator
  • Java Program to Reverse the Given Number
  • Java Program to Print Number in the Given Data Type
  • Program to Demonstrate Skipping using Continue
  • Program to find whether entered character is a vowel or Consonant
  • Java Program to Calculate the Sum of Digits of Given Number
  • How to swap two numbers using only two variables
  • Checking the Given Number is Armstrong or Not
  • Average an Array of Values
  • Display ASCII Code Instead of Character
  • Comparison of Two Variable using If
  • Printing Table In java using While Loop
  • Generate Random Number Using Math.Random Function
  • To Find roots of Quadratic Equation
  • Performing Arithmetic Opration on Two Variable
  • Concatenation of Two String in Java
  • Command Line Argument in JAVA
  • Java Hello World Program
  • Calculate Circle Perimeter | Java Program
  • Calculate the Area of Circle | Java Program
  • To Find Whether Given Year is a Leap Year or not
  • Popular
  • Recent
  • Archives

Total Pageviews

Sparkline

Followers

Popular Posts of This Week

  • Java program to create a Binary Heap and Perform various operation
    A binary heap (min-heap) is a complete binary tree with elements from a partially ordered set, such that the element at every node is less ...
  • Sort an Integer array with Bucket Sort
    Here is a java program to Sort an Integer array with Bucket Sort class BucketSort { public int[] bucketSort(int[] array) { /...
  • Reading large excel files
    By using this we can read excel sheets having large size package com.excel.reader; import java.io.File; import java.io.FileOutputStream;...
  • Stack implemented as array - Data Structure
    // Stack implemented as array public class ArrayStack<T> { private T[] stack; private int numElements = 0; // points to s...
  • To Sort an Interger Array using Shell Sort
    To Sort an Interger Array using Shell Sort class ShellSort { public static int[] shellSort(int[] array) { int N = array.length; ...
  • Implementation of a basic generic tree, with labels of type T - Data Structure
    // This implements a basic generic tree, with labels of type T, // pointer to the parent node, and a singly linked list of children nodes...
  • Create an Adjacency matrix Graph and perform Add and Remove operation
    import java.util.ArrayList; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Queue; import...
  • Sudoku Puzzle Game in Java
    import java.io.*; import java.util.*; public class SudokuSolver { public static void main(String[] args) throws Exception { /...
  • Merge-Sort Algorithm implementation in JAVA
    Merge-Sort Function void MergeSort(int low, int high) // a[low : high] is a global array to be sorted. // Small(P) is true if there...
  • Image Resizing using JAI
    Images of different formats like jpeg,png,tiff,bmp,fpx,pnm etc can be resized to a different size using Java Advanced Imaging import java...
Powered by Blogger.

Archives

  • ▼  2014 ( 4 )
    • ▼  August ( 4 )
      • Java program to create a Binary Heap and Perform v...
      • Create an Adjacency matrix Graph and perform Add a...
      • To Sort an Interger Array using Shell Sort
      • Sort an Integer array with Bucket Sort
  • ►  2013 ( 6 )
    • ►  August ( 1 )
    • ►  April ( 5 )
  • ►  2012 ( 673 )
    • ►  November ( 9 )
    • ►  October ( 223 )
    • ►  September ( 272 )
    • ►  August ( 2 )
    • ►  June ( 1 )
    • ►  February ( 67 )
    • ►  January ( 99 )
 

Our Blogs

  • Linux Tutorial
  • C Programming Tutorial

Labels

  • Agile Methodology ( 1 )
  • Algorithm ( 3 )
  • AntiSamy ( 1 )
  • Arithmetic Operation ( 1 )
  • Array Example ( 9 )
  • ArrayList Examples ( 11 )
  • Average an Array of Values ( 1 )
  • Barcode Example ( 1 )
  • Basic Java Programs ( 34 )
  • Bing API Example ( 2 )
  • BitSet Example ( 1 )
  • Boolean Example ( 1 )
  • Bouncy Castle API ( 1 )
  • Break Statement ( 2 )
  • BufferedReader Example ( 2 )
  • Calendar Example ( 1 )
  • Chart Generation Example ( 1 )
  • Command Line Argument ( 1 )
  • Comparator Example ( 1 )
  • Concatenation of String ( 1 )
  • Continue Statement ( 1 )
  • Control Structure ( 1 )
  • Copy File Example ( 1 )
  • CRC Example ( 1 )
  • CSV Example ( 6 )
  • Data Structure ( 5 )
  • Date Example ( 2 )
  • Directory Example ( 1 )
  • Do - While Loop Example ( 1 )
  • Domino Database ( 1 )
  • Email Example ( 8 )
  • Encryption Example ( 3 )
  • Excel Example ( 15 )
  • Factorial Example ( 1 )
  • File Upload Example ( 1 )
  • Find Roots of Quadratic Equation ( 1 )
  • FTP Example ( 2 )
  • Graph Examples ( 1 )
  • Greater between Two Numbers ( 1 )
  • GSON Library ( 1 )
  • HashMap Example ( 1 )
  • HashSet Example ( 1 )
  • Hello World Program ( 1 )
  • If Condition ( 2 )
  • Inner Class Example ( 1 )
  • iText Example ( 3 )
  • JAR File ( 1 )
  • JAVA Applet ( 1 )
  • Java Applications ( 1 )
  • Java AWT Example ( 9 )
  • Java Certification ( 1 )
  • Java Class Examples ( 15 )
  • Java Collection Example ( 1 )
  • Java Command Example ( 4 )
  • Java Constructor Examples ( 1 )
  • Java Currency Example ( 1 )
  • Java Database Example ( 3 )
  • Java Date and Time Example ( 3 )
  • Java DateFormat Example ( 3 )
  • Java Examples ( 2 )
  • Java Exception Example ( 5 )
  • Java File Example ( 22 )
  • Java GUI Example ( 1 )
  • Java Image Examle ( 3 )
  • Java Inheritance Example ( 3 )
  • Java Input Output Example ( 1 )
  • Java IO Example ( 3 )
  • Java Jar Example ( 1 )
  • Java JSON Example ( 3 )
  • Java Mail Examples ( 4 )
  • Java Map Example ( 5 )
  • Java MapReduce Example ( 2 )
  • Java MultiThreading Example ( 7 )
  • Java Network Example ( 9 )
  • Java Package ( 1 )
  • Java Programs ( 1 )
  • Java RMI ( 1 )
  • Java Robot Class Examples ( 2 )
  • Java Runtime Example ( 1 )
  • Java Swing Example ( 9 )
  • Java Util Example ( 1 )
  • Java Vector Example ( 4 )
  • Java Voice Example ( 1 )
  • Java Webservice Example ( 1 )
  • Java XML Example ( 3 )
  • Java Zip Class Examples ( 2 )
  • JDBC ( 9 )
  • JDK Version Comparison ( 1 )
  • JFrame Example ( 3 )
  • JOptionPane Dialog Example ( 1 )
  • JPanel Example ( 1 )
  • JSP Example ( 2 )
  • JSTL Example ( 1 )
  • jUnit Example ( 2 )
  • LinkedList Example ( 2 )
  • List Example ( 1 )
  • Long Variable ( 1 )
  • Lottery Nubmer ( 1 )
  • MD5 Hashing Example ( 3 )
  • Memory Management Example ( 1 )
  • Method Override ( 1 )
  • MIDI Sound ( 8 )
  • Module Operator Example ( 2 )
  • Multiplication Table ( 1 )
  • Observer Interface Example ( 1 )
  • Operator Example ( 5 )
  • Pagination ( 1 )
  • Palindrome Number ( 1 )
  • Pass By Reference Example ( 1 )
  • Pass By Value Example ( 1 )
  • PDF File Example ( 3 )
  • PDF Generation Example ( 4 )
  • Pre and Post Operator ( 2 )
  • Prime Number ( 3 )
  • Progress Bar Example ( 1 )
  • Property List Example ( 2 )
  • Random Function ( 7 )
  • Recursion Example ( 2 )
  • Regex Example ( 2 )
  • Remote Host Example ( 2 )
  • Robot Class ( 4 )
  • Searching Example ( 3 )
  • Slideshow ( 1 )
  • Sorting Example ( 7 )
  • SpringLayout Example ( 1 )
  • Stack Example ( 4 )
  • Static Variable ( 1 )
  • StreamTokenizer Example ( 2 )
  • String Example ( 19 )
  • Struts2 Example ( 1 )
  • Sum of Digits ( 1 )
  • Swap Two Numbers ( 1 )
  • Switch Case ( 3 )
  • Tapestry Components ( 1 )
  • Thumbnail Example ( 2 )
  • TimerTask Example ( 2 )
  • To Calculate Volume ( 1 )
  • To Check Armstrong Number ( 1 )
  • Tree Example ( 1 )
  • TreeMap Example ( 1 )
  • TreeSet Example ( 1 )
  • Two Dimensional Array Example ( 1 )
  • UUID ( 1 )
  • Validation Example ( 2 )
  • Variable Casting ( 1 )
  • While Loop ( 1 )
  • XML Parsing ( 7 )
  • XSS Attacks ( 1 )
  • Zip File ( 15 )

Popular Posts

  • Creating Dynamic Macro Enabled Excel by Java
    We can create a dynamic macro enabled excel by java: We need to create a excel sheet template with macro on server. we can copy the...
  • Java program to create a Binary Heap and Perform various operation
    A binary heap (min-heap) is a complete binary tree with elements from a partially ordered set, such that the element at every node is less ...
  • To Sort an Interger Array using Shell Sort
    To Sort an Interger Array using Shell Sort class ShellSort { public static int[] shellSort(int[] array) { int N = array.length; ...
  • Implementation of a basic generic tree, with labels of type T - Data Structure
    // This implements a basic generic tree, with labels of type T, // pointer to the parent node, and a singly linked list of children nodes...
  • Create an Adjacency matrix Graph and perform Add and Remove operation
    import java.util.ArrayList; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Queue; import...
  • Merge-Sort Algorithm implementation in JAVA
    Merge-Sort Function void MergeSort(int low, int high) // a[low : high] is a global array to be sorted. // Small(P) is true if there...
  • Sort an Integer array with Bucket Sort
    Here is a java program to Sort an Integer array with Bucket Sort class BucketSort { public int[] bucketSort(int[] array) { /...
  • Printing Table In java using While Loop
    Here is a Java Program to Print the Table public class Table { public static void main(String[] args) { int no = Integer.p...
  • Stack implemented as array - Data Structure
    // Stack implemented as array public class ArrayStack<T> { private T[] stack; private int numElements = 0; // points to s...
  • Java Program to Generate the Lottery Number between 1 to 49
     A lottery requires that you select six different numbers from the integers 1 to 49. Write a program to do this for you and generate five s...
 
 
© 2011 Java Programs and Examples with Output | Designs by Web2feel & Fab Themes

Bloggerized by DheTemplate.com - Main Blogger