Question

I have MVC 4 Application and im using google maps to render my locations by retrieving latitude and longitude from the database.(My database is updated automatically by wcf data service through mobile device.)

In MVC Application i want to refresh the google map automatically in timely manner. Following is my index page(Index.cshtml).

 @model IEnumerable<MvcApplication17.Models.Train>
<div id="MapLocators">
    @Html.Partial("Map_Locator", Model)
</div>


<script type="text/javascript">

$(function () {
    setInterval(function () { $('#MapLocators').load('/Home/GetMap'); }, 3000); 
});

</script>

Here is my Partial View under Home(Map_Locator.cshtml),

@model IEnumerable<MvcApplication17.Models.Train>
<div id="content-container">

<div id="map_canvas">
</div>
</div>


<script type="text/javascript">

google.maps.event.addDomListener(window, 'load', function(){


    var bounds = new google.maps.LatLngBounds();
    var mapoptions = { zoom:6}; //map options
    var map = new google.maps.Map(document.getElementById('map_canvas'), mapoptions);

    map.markers = [];

    @foreach(var item in Model)
{
    <text>

    var poiLatLang = new google.maps.LatLng( @item.Latitude, @item.Longitrude);
    var image = 'images/Train station.png';


    var marker = new google.maps.Marker({
        position: poiLatLang ,
        map: map,
        icon: image
    });


    bounds.extend(marker.position);
    map.markers.push(marker);
    </text>
}



    map.fitBounds(bounds);

});
</script>
<script type="text/javascript"
    src="http://maps.google.com/maps/api/js?sensor=false"></script>

Here is my Home Controller,

    private TestContext db = new TestContext();

 [OutputCache(NoStore = true, Location = OutputCacheLocation.Client, Duration = 3)] 
    public ActionResult GetMap()
    {


        return PartialView("Map_Locator",db.Trains.ToList());

    }

The problem is index page show the google maps only in first application loading stage and it doesn't refresh automatically.

Thanks

Was it helpful?

Solution

I solved the problem by calling map load function in following way,

<script>
$(function () {
    setInterval(function () { $('#MapLocators').load('/Home/GetMap',function{}); }, 20000);
});

</script>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top