简体   繁体   中英

how to use json ajax for google map markers

I try to use the Json Ajax for google map markers.So after clicking on the button run Ajax, I get a problem with it. it's not display markers Should change be made? Where is my problem? this is My Action after run ajax:

      [HttpPost]
    public ActionResult AsMapAjax(string jobid,string subid,string Searchitem)
    {
        string markers = "[";
        foreach (var item in UnitOfWork.WD.GetAll())
        {
            markers += "{";
            markers += string.Format("'title': '{0}',", "Test");
            markers += string.Format("'lat': '{0}',", item.Lat);
            markers += string.Format("'lng': '{0}',", item.Lng);
            markers += string.Format("'description': '{0}'", "www.google.com");

            markers += "},";
        }
        markers += "];";

        var mark= new MvcHtmlString(markers);
        return Json(new { success = true, responseText = mark }, JsonRequestBehavior.AllowGet);


    }
}

and my jquery ajax(scripts):

navigator.geolocation.getCurrentPosition(function (p) {
    var latlng = new google.maps.LatLng(p.coords.latitude, p.coords.longitude);

    var mapOptions = {
        center: latlng,
        zoom: 12,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    var infoWindow = new google.maps.InfoWindow();
    var map = new google.maps.Map(document.getElementById("dvMap"), mapOptions);
    //You re Here
    var iconoMarca = "../../images/URHere.gif";
    mymarker = new google.maps.Marker({
        animation: google.maps.Animation.DROP,

        map: map,
        icon: iconoMarca,
        position: latlng

    });
      $('#prt').on('click', function () {
        var Subid = document.getElementById("bluee").value;
        var jobid = document.getElementById("Jobs").value;
        var Searchitem = document.getElementById("SearchItem").value;
        $.ajax({
            type: "post",
            url: "/My/AsMapAjax",
            dataType: 'json',


            data: { subid:Subid,jobid:jobid,Searchitem:Searchitem},
            success: function (response) {
                if (response != null && response.success) {
                    //alert(response.responseText);
                    markers=response.responseText;

                } else {

                    alert("there is a problem!");
                }
            },
            error: function (response) {
                alert("Sorry!try again please.");

            }


        }

)

        ///////
        //label
        var  numberMarkerImg = {
            url: '../../images/shapemarker.png',
            size: new google.maps.Size(32, 38),
            scaledSize: new google.maps.Size(32, 38),
            labelOrigin: new google.maps.Point(21,42)
        };
        var markerLabel = 'Test';


        for (i = 0; i < markers.length; i++) {

            var data = markers[i]
            var myLatlng = new google.maps.LatLng(data.lat, data.lng);

                var marker = new google.maps.Marker({
                position: myLatlng,
                map: map,
                //label
                label:markerLabel ,
                title: data.title,
                icon:numberMarkerImg,
                animation: google.maps.Animation.DROP


            });


            ( function (marker, data) {
                google.maps.event.addListener(marker, "click", function (e) {
                    infoWindow.setContent(data.description);
                    infoWindow.open(map, marker);
                    window.location.href = "/My/sargarmi";

                });
            })
         (marker, data);

        }


        google.maps.event.addDomListener(window, "resize", function() {
            var center = map.getCenter();
            google.maps.event.trigger(map, "resize");
            map.setCenter(center);
        });

    });

but the markers not display ! how to fix this problem? or is other way for this question? thanks a lot

Your question does not explain what specific problem you are experiencing. So i am going to give you a simple - working solution which improves some of the stuff you did.

Let's start with your server method. You are building the stringified version of a json array by string concatenation. That is unnecessary and error prone. Why not let the JSON serializer which is part of the mvc framework to do that for you ?

Create a simple class to represent your marker

public class Marker
{
    public string Title { set; get; }
    public double Lat { set; get; }
    public double Lng { set; get; }
}

Now in your action method, Build a list of this Marker class and you can pass that to the Json method.

[System.Web.Mvc.HttpPost]
public ActionResult AsMapAjax(string jobid, string subid, string Searchitem)
{
    //Hard coded for demo. You may replace with values from db
    var list = new List<Marker>
    {
        new Marker() { Title="AA" ,Lat =  -33.890542, Lng=151.274856 },
        new Marker() { Title="BB", Lat =  -33.923036, Lng=151.259052 },
        new Marker() { Title="CC" ,Lat =  -34.028249, Lng=151.157507 },
    };
    return Json(new { success = true, responseText = list });
}

Now in your client side, you make the ajax call to this action method, read the response coming back and add markers.

$(function() {
    $('#prt').on('click', function() {
        initMap();
    });
});

function initMap() {
    //read the parameter values you want to send to server
    var searchItem =$("#SearchItem").val();
    var jobs=$("#Jobs").val();
    var subid = $("#bluee").val();

    var map = new google.maps.Map(document.getElementById('map'),
        {
            zoom: 8
        });
    var url = "@Url.Action("AsMapAjax", "Home")";

    $.post(url, { searchTerm: searchItem,jobid: jobs,subid : subid },function(res) {
            if (res.success) {
                var latLng;
                $.each(res.responseText,function(i, item) {
                        latLng = new google.maps.LatLng(item.Lat, item.Lng);
                        var marker = new google.maps.Marker({
                            position: latLng,
                            map: map
                        });

                    });
                map.setCenter(latLng);
            }
    });
}

I am using the Url.Action method to generate the correct relative url to the action method as my script was inside a razor code block. If you are using this code in an external javascript file, follow the solution described in this post to handle that case

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM