How to locate multiple addresses on google maps with perfect zoom


First of all I am writing this article to deal with this very specific problem since I saw a lot people looking to get this achieved. I won't be describing the Google Maps API in detail because for this you can go through the Google Maps API official documentation.

So here we are going to talk about a very common problem that many face while integrating google maps with their web application on client side.You will learn how to place mlutiple addresses on google map and scale it so that each of the address fit in the given amount of space with a perfect zoom.Although I suppose google has a good documentation but still it takes time to assemble it  to the perfection. I would like to share my experience here. May be this helps a few of you who have been looking for it.

Before starting I would just like to confirm that google maps Javascript API v3 is to be included to execute the code I am about to mention.
Here is the piece of line that you need to include.
  
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
 
This is only for personal use. Please refer to Loading the Google Maps JavaScript API for Business-specific instructions.
Basically you need to append the API key for business usage.

Google Maps API has a very basic and most used feature that takes latitude and longitude as input and places it on the map and renders it. You might be wondering that how would I get the latitude and longitude. So Google do have a solution for that too. Its Geo-Location API.

Google Geolocation API
This API takes the address and will return you the list of locations(lat,long,etc).
Communication is done over HTTPS using POST. Both request and response are formatted as JSON, and the content type of both is application/json.
These couple lines will do the job for you.

 
        var addr = "My Address";
        var geocoder = new google.maps.Geocoder();
        geocoder.geocode({
            'address': addr
        }, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                // you have your collection of matching results with you here.
            } else    {
                // alert(status);
            }
        });

So in "results" we have a array of locations that matches with the given address string.

Now we need to locate the location as a marker on the google maps.
First we need to initialize the Google Maps.
       
           
 
   var myOptions = {
                zoom: 16,
                center: results[0].geometry.location,
                mapTypeId: google.maps.MapTypeId.ROADMAP
          }
   map = new google.maps.Map(document.getElementById("map-canvas"), myOptions);
You have many more options available that you can refer to google maps API documentation. Currently we have just defined the type of map, the location where it need to center the map and the default zoom.
Once the map is initialized we can place multiple markers that we need to place on map. Here is an example.
 
for(var i=0; i<results.length; i++ )    {
            var marker = new google.maps.Marker({
                map: map,
                position: results[i].geometry.location
            });
        }
        
Above lines of code will place all the locations on the map.
Now to associate the custom address string with the markers you can use info windows. You can add an mouseover or a click or any other event on markers that shows up the info window with your own custom address string.
Below lines of code will do the work perfectly.
 
 var infowindow = new google.maps.InfoWindow();
 google.maps.event.addListener(marker, 'mouseover', (function(marker) {
            return function() {
                var content = address;
                infowindow.setContent(content);
                infowindow.open(map, marker);
            }
          })(marker));

You can modify the event as per convenience. I have used mousover in above piece of code.
Now the bigger question comes into picture that how will you scale the map is perfectly zoom and centered with all the markers placed.
Well, when you are dealing with google maps its not a tough task. Here is how you are able to achieve this.    
 
            //Initialize bounds
            var bounds = new google.maps.LatLngBounds();
            for(var i=0; i<results.length; i++ )    {
                var marker = new google.maps.Marker({
                    map: map,
                    position: results[i].geometry.location
                });
               
                // Below line of code will tell the map how much it need to scale.
                bounds.extend(marker.position);
                map.fitBounds(bounds);
            }
"bounds" maintains the list of locations for which it need to scale the map.
Here is JSFiddle link where you can execute above code.
In this example whatever you add to to the input box gets added as a marker in the map and the map automatically gets scaled accordingly

I hope you find it very easy and this helps you playing with google maps.





Related

programming 8275212110592545848

Post a Comment

  1. Wow you have listed almost everything.. !

    ReplyDelete
  2. George Malakov7 March 2014 at 02:59

    Nice POST, I naturally prefer KDE interface on Linux mainly because I used it a long time, but it's nice to see that ubuntu Linux has more XP like looking alternatives. The new distribution is with a not very friendly interface.

    ReplyDelete
  3. Don't get Linux Mint 13 Maya.
    Wait for Linux Mint 17 Qiana, which comes out by the end of May. It is the next LTS.
    It has better security than Mint 13 and will be supported longer.

    ReplyDelete
  4. Of the three, my vote goes to Linux Mint 13 Maya which I currently use on my desktop work PC. I used to dislike Cinnamon and used the MATE version and modified it to have the traditional Gnome 2/MATE look but I'm now comfortable with Cinnamon.

    Zorin OS is OK but I find it a bit too heavy on resources, even the Lite version and Ifind Lubuntu a bit too lite for my needs in termns of what comes with the DVD/CD and whilst LXDE perhaps is the best of lite desktops in terms of graphical desktop goes, my first choices would either be MATE or Cinnamon.

    Another distribution which is intended as a Windows XP replacement is Linux Lite, an Ubuntu 12.04 LTS-based distribution with an Xfce desktop but unlike Lubuntu, Xubuntu, Bodhi and other lite distributions, Linux Lite comes with fully-featured applications such as LibreOffice rather than lite versions such as Abiword.

    https://www.linuxliteos.com/index.html



    And on Distrowatch
    http://distrowatch.com/table.php?distribution=lite



    Whilst graphical, photo and video editing, some non-free codecs and components, Wine, Steam OS, etc. are not installed by default, Linux Lite's menu has options to install them in sets post-installation.

    Whilst configuration of application shortcut icons on the Xfce panel isn't as convenient as for MATE, Cinnamon or even LXDE, I can still live with Linux Lite's Xfce desktop if required.

    Linux Lite is also recognised as one of the best for use on netbooks and I installed it on my Lenovo S10 and it ran beautifully.


    It's also very memory efficient for an Ubuntu-based distribution, and uses around 110MB or so of RAM upon boot up. It's also fast and responsive.

    A word of caution though. Num Lock is on on by default when the Linux Lite live DVD boots up, which poses problems on notebooks and netbooks where numeric and alpha keys are overlayed on their keyboard but not with a desktop PC keyboard.

    This resulted in some of the characters of my WiFi passphrase being the wrong ones. So you must first manually turn Num Lock off before proceeding to connect to WiFi or even to install, otherwise, you may later find that the password you keyed in dusing installation may not what you intended.

    Also remember to turn Num Lock off after your FIRST boot up from hard disk and after that it will rember that Num Lock is off by default on subsequent reboots. Better still configure Num Lock off by default in your BIOS.


    When installing on a netbook, it's also worth having it connected to the router by a LAN cable, since you may have to subsequently install the proprietary WiFi module driver, especially if it's a Broadcom.



    For a PC model up to say seven years old, I'd use Linux Mint but for an older Pentium 4 model with say 512 of RAM and no accelerated graphics or for a netbook, i'd use Linux Lite.


    However, Linux Lite live USB did not run well on some netbooks such as a Dell I tried it on but very well on my Lenovo S10.


    I wouldn't use a lite Ubuntu-based derivative above 10.04 LTS on really old PCs with a Pentium 3 processor and 256MB of RAM as . For that, I've found Knoppix or Debian Wheezy with an LXDE desktop to be more suitable.


    If it has 384MB or more of RAM, I recommend Snowlinux 4 Glacier based on Debian Wheezy.


    Yesterday, I installed it on an old Pentium III-based Dell OptiPlex GX110 with 384MB of RAM and it is pretty fast. It's MATE desktop is laid out in "Windows XP" style similar to Linux Mint.

    ReplyDelete
  5. I'm waiting with bated breath for Qiana and will upgrade when it comes out.

    ReplyDelete

emo-but-icon

Translate

 

Recent Posts

comments

Recent Comments Widget

Join Us

 

Sponsored By

Recommended for you

get social

item