su star su star - 3 months ago 21
JSON Question

Assign the JSON string value to Latitude and Longitude in google.maps.LatLng(lat,lon) in MVC 4

Controler Action code

[HttpGet]
public JsonResult findlatlon()
{

Models.Vehicle_Tracking_SystemEntities entities = new Vehicle_Tracking_SystemEntities();
var latlon = entities.LatLangs.ToList();
return Json(new { AddressResult = latlon }, JsonRequestBehavior.AllowGet);
}


findlatlon.cshtml View code



{ ViewBag.Title = "findlatlon"; }
<script src="~/Scripts/jquery-1.8.2.js"></script>
<script src="~/Scripts/jquery-1.8.2.min.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
<script src="http://maps.googleapis.com/maps/api/js?key=AIzaSyCM7G5ruvunb0K7qxm6jb1TssJUwROqs-g" type="text/javascript"></script>

<script type="text/javascript">
$(document).ready(function() {
var myMarkers = [];
$.ajax({
async: false,
type: "POST",
dataType: "json",
url: '@Url.Action("findlatlon", "Home")',
data: '{}',
success: function(result) {
//get address from controller action.....
myMarkers = result.AddressResult;
}

});

//init google map
function googleMap() {
//alert("Hellooooooo");//alert
var mapOptions = {
center: new google.maps.LatLng(myMarkers[0].Latitude, myMarkers[0].Langitude),
zoom: 2,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
//alert(myMarkers[0].Latitude);//alert
var infoWindow = new google.maps.InfoWindow();
var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
for (i = 0; i < myMarkers.length; i++) {
data = myMarkers[i];
var marker = new google.maps.Marker({
position: new google.maps.LatLng(data.Latitude, data.Langitude),
map: map
});
(function(marker, data) {
google.maps.event.addListener(marker, "click", function(e) {
infoWindow.setContent(data.Location_Adress);
infoWindow.open(map, marker);
});
})(marker, data);
}
}
//....
google.maps.event.addDomListener(window, 'load', googleMap);


})
</script>

<div id="map_canvas" style="border-top: none; width: 100%; margin-top: -1px;
height: 250px; background-color: #FAFAFA; margin-top: 0px;">
</div>




Out-Put


{"AddressResult":[{"Id":1,"Latitude":"33.9982","Langitude":"71.4999","Address":"Peshawar","Image":null,"Title":"Peshawar"}]}


So here the AJAX call the controller and controller retrieve the longitude and latitude from the database and return it in json string to view like the above output.

But here I wants that the Latitude and longitude value which return by the json is assign to the

center:
new google.maps.LatLng(myMarkers[0].Latitude, myMarkers[0].Langitude)

And I wants to show the location on google map according to the Lat and Long

Div Div
Answer

Here is an example of displaying google map on button clicked, which display accordingly your response, make sure use 'markers.push(v);' need to make change accordingly your code.

 var markers = [];
    window.onload = function () {
        $('#getMap').click(function () {
            var deviceId = $('#deviceNumber').val();
            if (deviceId != null || deviceId != "") {
                $.ajax({
                    type: "GET",
                    url: url,
                    data: {},
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (data) {
                        $.each(data, function (i, v) {
                            markers.push(v);
                        });
                        var mapOptions = {
                            center: new google.maps.LatLng(markers[0].Latitude, markers[0].Longitude),
                            zoom: 10,
                            mapTypeId: google.maps.MapTypeId.ROADMAP
                        };
                        var map = new google.maps.Map(document.getElementById("dvMap"), mapOptions);
                        var infoWindow = new google.maps.InfoWindow();
                        var lat_lng = new Array();
                        var latlngbounds = new google.maps.LatLngBounds();
                        for (i = 0; i < markers.length; i++) {
                            var data = markers[i]
                            var myLatlng = new google.maps.LatLng(data.Latitude, data.Longitude);
                            lat_lng.push(myLatlng);
                            var marker = new google.maps.Marker({
                                position: myLatlng,
                                map: map,
                                title: data.title
                            });
                            latlngbounds.extend(marker.position);
                            (function (marker, data) {
                                google.maps.event.addListener(marker, "click", function (e) {
                                    infoWindow.setContent(data.description);
                                    infoWindow.open(map, marker);
                                });
                            })(marker, data);
                        }
                        map.setCenter(latlngbounds.getCenter());
                        map.fitBounds(latlngbounds);

                        //***********ROUTING****************//

                        //Initialize the Path Array
                        var path = new google.maps.MVCArray();

                        //Initialize the Direction Service
                        var service = new google.maps.DirectionsService();

                        //Loop and Draw Path Route between the Points on MAP
                        for (var i = 0; i < lat_lng.length; i++) {
                            if ((i + 1) < lat_lng.length) {
                                var src = lat_lng[i];
                                var des = lat_lng[i + 1];
                                service.route({
                                    origin: src,
                                    destination: des,
                                    travelMode: google.maps.DirectionsTravelMode.DRIVING
                                }, function (result, status) {
                                    if (status == google.maps.DirectionsStatus.OK) {
                                        var path = new google.maps.MVCArray();
                                        var poly = new google.maps.Polyline({
                                            map: map,
                                            strokeColor: '#4986E7'
                                        });
                                        poly.setPath(path);
                                        for (var i = 0, len = result.routes[0].overview_path.length; i < len; i++) {
                                            path.push(result.routes[0].overview_path[i]);
                                        }
                                    }
                                });
                            }
                        }
                    },
                    error: function () {
                        alert('error');
                    }
                });
            }
        });
    }

Hope this helps!