简体   繁体   English

如何将 json ajax 用于谷歌地图标记

[英]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.我尝试将 Json Ajax 用于谷歌地图标记。所以在单击按钮运行 Ajax 后,我遇到了问题。 it's not display markers Should change be made?它不是显示标记 应该进行更改吗? Where is my problem?我的问题在哪里? this is My Action after run ajax:这是运行 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):和我的 jquery ajax(脚本):

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.您正在通过字符串连接构建 json 数组的字符串化版本。 That is unnecessary and error prone.这是不必要的并且容易出错。 Why not let the JSON serializer which is part of the mvc framework to do that for you ?为什么不让作为 mvc 框架一部分的 JSON 序列化程序为您做这件事呢?

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.现在在您的操作方法中,构建此 Marker 类的列表,您可以将其传递给Json方法。

[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.现在在您的客户端,您对该操作方法进行 ajax 调用,读取返回的响应并添加标记。

$(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.我正在使用Url.Action方法为Url.Action方法生成正确的相对 url,因为我的脚本位于 razor 代码块内。 If you are using this code in an external javascript file, follow the solution described in this post to handle that case如果你是在一个外部JavaScript文件中使用此代码,请介绍的解决方案这个帖子来处理这种情况

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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