D
D
damir872015-11-03 12:10:34
JavaScript
damir87, 2015-11-03 12:10:34

How to display a large number of objects in 2gis?

How to work with a large number of objects in 2Gis, is there an analogue in 2gis or something similar like objectmanager in Yandex maps? Or an implementation with ajax loading data in the visible area, but so that the map does not slow down, now when moving the map, I take the bound of the visible area and send it to the server and get points in these coordinates, but if I zoom, then, accordingly, a large coverage of 10,000 points or more at once and already freezes are visible.

map.on('moveend', function () {
               //получаю точки видимой прямоугольной области
                var coords = map.getBounds();
                var points = [];
                points.push(coords.getSouthWest().lat);
                points.push(coords.getSouthWest().lng);
                points.push(coords.getNorthEast().lat);
                points.push(coords.getNorthEast().lng);

                var theData = JSON.stringify(points);
                $.ajax({
                    cache: false,
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    url: "/Flat/JsonSearchByCoords",
                    data: { points: theData },
                    success: function (data) {
                        //получаю с бд точки в видимой прямоугольной области и передаю в функцию, которая
                        //отрисует их на карте
                        $.onBoundChange(data, objects);

                    },
                    error: function (xhr, ajaxOptions, thrownError) {
                        alert("Ajax Failed!!!");
                    }
                }); 
            });

            });

            $.onBoundChange = function sendParams(jsonArray, dataArray) {
                
                 var myIcon2 = DG.icon({
                    iconUrl: 'Content/images/gohome.png',
                    iconSize: [30, 32]
                });
                var marker;
                // обработка координат для установки маркеров
                for (var i = 0; i < compare.length; i++) {
                    var title = "<div class='item bft-object_md'>\
                                <div class='row'>\
                                    <div class='col-xs-12 col-sm-5'>\
                                        <div class='tail tail_height m-b-10 maw-250'>\
                                            <a href='#' target='_blank'>11\
                                            </a>\
                                        </div>\
                                    </div>\
                                    <div class='omega col-xs-12 col-sm-7'>\
                                        <div class='bft-object__caption bft-object__caption_static p-l-0 p-b-5 p-t-0'>\
                                            <b><a href='#' target='_blank'>" + compare[i].Street + "</a></b>\
                                        </div>\
                                        <div class='p-b-5 p-t-0'> " + compare[i].House + " </div>\
                                        <div title=\"{7}\">\
                                            <a class='price btn-success btn-sm btn p-r-15 maw-100p' href='#' target='_blank'>\
                                                <span class='item d-i-b'>" + i + "</span>\
                                                <span class='item d-i-b'>\
                                                    <span>{5}</span> <br>\
                                                    <span class='cashless'> " + compare[i].Street + " </span>\
                                                </span>\
                                            </a>\
                                        </div>\
                                    </div>\
                                </div>\
                            </div>";

                    marker = DG.marker([compare[i].Lattitude, compare[i].Longitude], { icon: myIcon2, title: title });
                    marker.bindPopup(title);
                    markers.addLayer(marker);
                }
                $('#DGMap').removeClass('loading');
               //добавляет все точки на карту
                map.addLayer(markers);

            }

Answer the question

In order to leave comments, you need to log in

3 answer(s)
D
damir87, 2015-11-05
@damir87

Maybe someone will need it, a gray sketch of the implementation, of course, you need to make the code a little prettier to make it useful for someone to
call the button to build a map

$("#gisSubmit").on("click", function () {
        $.ajax({
            cache: false,
            type: "GET",
            contentType: "application/json; charset=utf-8",
            dataType: 'json',
            url: "/Flat/JsonMainFlat",
            data: {},
            success: function (data) {
                $.setMarks(data, true);
            },
            error: function (xhr, ajaxOptions, thrownError) {
                alert("Ajax Failed!!!");
            }
        }); // end
    });

the function itself
$.setMarks = function setMark(json) {
    
    DG.then(function() {
        // загрузка кода модуля
        return DG.plugin('http://2gis.github.io/mapsapi/vendors/Leaflet.markerCluster/leaflet.markercluster-src.js');
    }).then(function() {
        var markers, map, marks = [], myObjects = [];
        var myIcon = DG.icon({
            iconUrl: 'Content/images/home.png',
            iconSize: [40, 42]
        });

        var myIcon2 = DG.icon({
            iconUrl: 'Content/images/gohome.png',
            iconSize: [30, 32]
        });
        map = DG.map('DGMap', {
            center: DG.latLng(parseFloat(json.Lattitude), parseFloat(json.Longitude)),
            zoom: 15,
            geoclicker: true,
            //minZoom: 10,
            //maxZoom: 17
        });

        markers = DG.markerClusterGroup({
            maxClusterRadius: 30,
            spiderfyDistanceMultiplier: 5
        });

        var coords = map.getBounds();
        marks.push(coords.getSouthWest().lat);
        marks.push(coords.getSouthWest().lng);
        marks.push(coords.getNorthEast().lat);
        marks.push(coords.getNorthEast().lng);

        searchByCoords(marks);
               
        map.on('moveend', function() {
            var isMoved = false;

            var retrievedObject = localStorage.getItem('testObject');
            var storage = JSON.parse(retrievedObject);

            if (storage != null && storage.length > 0 && !isMoved) {
                var theData = JSON.stringify(storage.length);
                flatsEquals(theData, storage);
            } else {
                searchByCoords(marks);
            }
        });

        function setPoints(points, isFlag) {
            var marker;
            if (!isFlag) myIcon = myIcon2;
            // обработка координат для установки маркеров
            for (var i = 0; i < points.length; i++) {
                myObjects.push(points[i]);
                var title = "<div class='item bft-object_md'>\
                                <div class='row'>\
                                    <div class='col-xs-12 col-sm-5'>\
                                        <div class='tail tail_height m-b-10 maw-250'>\
                                            <a href='#' target='_blank'>11\
                                            </a>\
                                        </div>\
                                    </div>\
                                    <div class='omega col-xs-12 col-sm-7'>\
                                        <div class='bft-object__caption bft-object__caption_static p-l-0 p-b-5 p-t-0'>\
                                            <b><a href='#' target='_blank'>" + points[i].Street + "</a></b>\
                                        </div>\
                                        <div class='p-b-5 p-t-0'> " + points[i].House + " </div>\
                                        <div title=\"{7}\">\
                                            <a class='price btn-success btn-sm btn p-r-15 maw-100p' href='#' target='_blank'>\
                                                <span class='item d-i-b'>" + i + "</span>\
                                                <span class='item d-i-b'>\
                                                    <span>{5}</span> <br>\
                                                    <span class='cashless'> " + points[i].Street + " </span>\
                                                </span>\
                                            </a>\
                                        </div>\
                                    </div>\
                                </div>\
                            </div>";

                marker = DG.marker([points[i].Lattitude, points[i].Longitude],
                {
                    icon: (i > 0) ? myIcon2 : myIcon,
                    title: title
                });
                marker.bindPopup(title).openPopup();
                markers.addLayer(marker);
            }
            return markers;
        }

        //поиск по координатам, получаем коорды видимой области и достаём все точки в заданной области
        function searchByCoords(marks) {
            var theData = JSON.stringify(marks);
            $.ajax({
                cache: false,
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: "/Flat/JsonSearchByCoords",
                data: JSON.stringify({ points: theData }),
                success: function(data) {
                    var objects = setPoints(data, true);
                    LocalStorage(data);
                    map.addLayer(objects);
                },
                error: function() {
                    console.log("Ajax Failed!!!");
                }
            });
        }

        //получаем все точки и добавляем на карту
        function getAllFlats(onMapMarks) {
            $.ajax({
                cache: false,
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: "/Flat/JsonAllFlats",
                data: {},
                success: function (data) {
                    var compare = diff(data, onMapMarks);
                    var objects = setPoints(compare, false);
                    map.addLayer(objects);
                },
                error: function() {
                    console.log("Ajax Failed!!!");
                }
            });
        }

        //проверяем количество точек(только число) на сервере и на клиенте в лок.хранилище
       // to_do желательно произвести оптимизацию
       function flatsEquals(theData, storage) {
            $.ajax({
                cache: false,
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: "/Flat/JsonEquals",
                data: JSON.stringify({ points: theData }),
                success: function(data) {
                    if (!data) {
                        getAllFlats(storage);
                    }
                },
                error: function() {
                    alert("Ajax Failed!!!");
                }
            }); // end
        }

        function convert(arr) {

            for (var k = 0, newArr = []; k < arr.length; k++) {
                newArr.push(arr[k].Lattitude + ';' + arr[k].Longitude);
            }
            return newArr;
        }
        //проверяем json_объекты и добавляем новые уникальные на карту и в сам json-обновляя в нём кол-во уникальных объектов
        function diff(arr1, arr2) {

            var tmpArr1 = convert(arr1),
                tmpArr2 = convert(arr2),
                result = [];

            for (var i = 0; i < arr1.length; i++) {
                if (tmpArr2.indexOf(tmpArr1[i]) == -1) {
                    result.push(arr1[i]);
                    myObjects.push(arr1[i]);
                }
            }
            //локальное хранилище
            LocalStorage(myObjects);

            return result;

        }

        //localStorage - локальное хранилище, хранение данных на клиенте, в случае если уже клиент посещал страницы
        //достаём точки из его хранилища, не обращаясь к бд
        function LocalStorage(json) {
            var testObject = json;

            //Помещаем объекты в хранилище
            localStorage.setItem('testObject', JSON.stringify(testObject));

            // получаем объект с хранилища, тестируем
            var retrievedObject = localStorage.getItem('testObject');

            console.log('retrievedObject: ', JSON.parse(retrievedObject));
        }

    });

K
kapuletti, 2015-11-03
@kapuletti

Can be implemented with add. module.
api.2gis.ru/doc/maps/examples/external-modules/#%D...

A
Artyom Egorov, 2017-09-03
@egoroof

https://github.com/2gis/general
https://github.com/2gis/markerdrawer

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question