Wednesday, June 15, 2011

Different map for a different browser!

            The title simply implies that detect the client's browser and then display the map accordingly! This is basically important when you are developing a map application for mobiles. Mobiles usually have a small screen and the maps that look brilliant on the desktops don't look the same on the mobile screens!

            Well, in my example, I am considering only two of the most popular browsers in use - Mozilla and IE. The application detects whether the client's browser is one of the two and then renders the map accordingly! If you are viewing the example in Mozilla, then you will see a 600 X 800px map, whereas if you are viewing it in IE, you will see a smaller 500 X 500px map! Here is the code...

<html>
<title>Basic Google Map Example - Detect browser and render map accordingly
</title>
<head>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false">
</script>
<script type="text/javascript">
var map;
function load()
{
    var useragent = navigator.userAgent;
    map = new google.maps.Map(document.getElementById("map_area"),
    {
        zoom: 6,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        center: new google.maps.LatLng(21.698265,79.035645)
    });
    if (useragent.indexOf('MSIE') != -1)
    {
        map_area.style.height = '500px';
        map_area.style.width = '500px';
    }
    else if (useragent.indexOf('Mozilla') != -1)
    {
        map_area.style.height = '600px';
        map_area.style.width = '800px';
    }
}
</script>
</head>
<body onload="load()">
<div id="map_area">
</div>
</body>
</html>

             The key focus point in this code is "navigator.userAgent". This detects the type, version, etc. of the current browser being used! The output of the above code will appear as seen in the images below!

Output - Browser used IE

 Output - Browser used Mozilla

            Please try on other browsers as well. Please leave a comment about the results you observe. Hope you like the post. Please leave your feedback here!