tags:

views:

264

answers:

2

I am developing travel portal for India in which i want to add Google Maps of each hotel which is saved in the database. My problem is how do I create the map dynamically?

+3  A: 

This is probably the best place to start:

http://code.google.com/apis/maps/documentation/introduction.html

MatrixFrog
+2  A: 

The following is a basic example using ASP.MVC for displaying a number of Hotels on a Google Map.

The domain object is Hotel:

public class Hotel
{
    public string Name { get; set; }
    public double Longitude { get; set; }
    public double Latitude { get; set; } 
}

You will need a repository to get some hotel objects. Use this in the Home controller in a method called HotelsForMap():

public ActionResult HotelsForMap()
{
    var hotels= new HotelRepository().GetHotels();
    return Json(hotels);
}

Create a partial view for the google map. Lets call it GoogleMap. It will need to contain:

  1. Reference to the google map api

    <script src="http://maps.google.com/maps?file=api&amp;amp;v=2&amp;amp;key=ABQIAAAAzr2EBOXUKnm_jVnk0OJI7xSosDVG8KKPE1-m51RBrvYughuyMxQ-i1QfUnH94QxWIa6N4U6MouMmBA" type="text/javascript"></script>
    
  2. jQuery to get Hotel objects from JSON call above

    $(document).ready(function(){ if (GBrowserIsCompatible()) { $.getJSON("/Home/HotelsForMap", initialize); } });

  3. jQuery to initialise map

    function initialize(mapData) {

    var map = new GMap2(document.getElementById("map_canvas"));
    map.addControl(new google.maps.SmallMapControl());
    map.addControl(new google.maps.MapTypeControl());
    
    
    var zoom = mapData.Zoom;
    map.setCenter(new GLatLng(mapData[0].Latitude, mapData[0].Longitude), 8);
    
    
    $.each(mapData, function(i, Hotel) {
        setupLocationMarker(map, Hotel);
    });
    

    }

  4. jQuery to set markers for hotels on the map

    function setupLocationMarker(map, Hotel) { var latlng = new GLatLng(Hotel.Latitude, Hotel.Longitude); var marker = new GMarker(latlng); map.addOverlay(marker); }

Finally, you will need a view that contains the partial view above. The view will need to have a div with an id of map_canvas as that is what is referenced in the initialize function above. The view should contain the following:

<h2>Hotels</h2>
<br />
<div id="map_canvas" style="width: 500; height: 500px">
     <% Html.RenderPartial("GoogleMap"); %>
</div>

Hopefully you can use some of this, even if you are not familiar with ASP.MVC.

Spear
thanks for your kind help