I will give you a simple example that will use Geocoding to find a location on a map based on user input in a text box. I will use Google Maps. To use Google Maps, you must add a script reference to their API. The syntax is like below :
It must be placed inside <head> tag before you initialize your maps. After that, you must define the HTML element that we will need. We will need a <div..> element as a map container, a textbox for user input and a button for submit the request. Here is the code :
After defining the html element, we must define the initialization function in javascript. It will be used to render a map, define the geocoder and the marker. Here is the code :
Here is the explanation :
geocoder is used to geocode the user input into the geographic coordinates.
latlng is used to give default position for the first request.
map is used to define a Google Maps object.
marker is used to define marker symbol on the map that show the location that the user searching for.
After define the initialization function, you must define the function that response to the user input. It will response to button click event.
This function get user input and place it in address variable. Then geocoder object will geocode the address and define the callback function that will be called when geocode process is done. The geocode process is asynchronous so we must define the callback function. It will check the GeocoderStatus. If the geocode process find a location based on the adress, the status will be OK, otherwise it will give error status. After find the right location, it will set the center of the map and the marker to that location so the user will know where is the place of the address based on user input.
Here is the screenshot of the web apllication :
You can download the complete code here. If you want to have a deeper look at Google Maps, you can find the complete tutorial from Google in Google Maps Javascript API.
If you have more question, please let me know. Hopefully this post will help you to understand the Geocoding mechanism.. Regards..!!! ^_^
No comments:
Post a Comment