loading...

Using the Bing API in a Java Application

cal_woolgar profile image Cal ・2 min read

Setting Up

My main task today has been to integrate Bing locations API within our platforms JAVA API so that we can do location lookups from the front-end.

To do this I first went and had a read of the documentation from Microsoft, giving myself a good overview of what the task would take, what I'd need to pass as parameters, and then what the response would be.

Locations API - Bing Maps

These are the 2 calls from the above link that I needed, the first being Find a Location by Query, and the second was Find a Location by Point. By using these 2 calls, they would allow me to search for an address using either a search term, like "London" or latitude and longitude values. I went ahead and took a look through these 2 calls to make sure I understood what they did and what was returned, I then copied the URL into my code so that I had it ready.

I then needed to make sure that I have an API key to actually authorize the API. This link showed me how to get that:

Getting a Bing Maps Key - Bing Maps

Calling API using RestTemplate

Then came the part of using the java restTemplate to call the API, this is quite simple and just requires some parameters, here's my code:

String locationUrl = "http://dev.virtualearth.net/REST/v1/Locations/" + point + "?key=" + key;

ResponseEntity<String> result = restTemplate.getForEntity(locationUrl, String.class);

return result.getBody();

This then returns the response that is specified on the URL, from there I created an object which had all of the JSON properties so that I could use GSON, and convert the JSON to an object. With that object, I then just picked out the properties I needed and put them in my response object which gets sent to the front-end.

Discussion

pic
Editor guide
Collapse
luccaprado profile image
Lucca Prado

Hi, I would go fot Spring Cloud OpenFeign as you can achieve a better code structure and, in my opinion, an better code

Collapse
cal_woolgar profile image
Cal Author

Thanks for the tip Lucca. I’m not overly experienced with Java and spring so still getting to grips with it, but taking a look at OpenFeign it looks like a better and cleaner way to write REST calls. I’ll take a look at using it!
Thanks for the advice!