Thursday, September 21, 2017

How to display GeoJson in Google Maps


      Earlier I wrote a post about how to create geojson objects in SQL Server. Today, I am going to show you how to display geoJson objects created by SQL Server in Google Maps. You can use Bing Maps or any other open source map providers to accomplish this task. I picked the Google Maps because I have already have an account and an API key with Google Maps.
   
     To be able to use Google Maps, you need to get an API key. Here is the link about how to create one. Dont' worry it's pretty simple and easy. I found a great Github source for geoJson files. I am going to use static links, If you create your geoJson dynamically in the SQL Server, your json should come from your IIS server.
   
     I am going to have a simple HTML page which is going to display Google Maps. Page is going to have bunch of buttons which are going to trigger JSON ajax calls to get GeoJson objects from a server. When the ajax calls completes, Google Maps API is going to take the geoJson and draw it on the map.

     First let's look at the HTML part. I am going to use a div container named map to display Google Maps. I will pass the the container's id to Google's API so it will know where to display the Google Map on the page. I need to pass my API key in the script element too. For security purposes, when you create your API key, you should specify which domain/s or url/s can use the API key you have created.



    Next, Let's look at the javascript code. I hard coded my geoJson endpoints on the top of the script. This should simulate calling IIS server which should trigger a call to SQL Server to create a GeoJson. The buttons on the top of the page gets one of these hard coded endpoints and loads the geoJson object from Github to simulate IIS call.Initialize function loads the Google map into the div that we specified.


   I have a simple jquery ajax call function which uses one of the links to load geoJson.



loadGeoJsonString function takes the loaded geoJson and adds it to the map. zoom function fires up after adding the geoJson object and it zooms in to the loaded object.



You can find this in action in my codepen post.

1 comment:

  1. Thanks for sharing best information. I am looking for google maps scraper free tool which helps in mining prospect data as per my selected niche.

    ReplyDelete