Настройка маркеров на основе переменных в JavaScript - PullRequest
0 голосов
/ 19 ноября 2018

Я пытаюсь создать другие маркеры на основе определенной переменной. На моей карте три координаты с информационным окном. Каждая координата имеет свой «Тип отчета» (пожертвование, запрос, катастрофа). Я пытаюсь настроить каждую координату, чтобы иметь разные маркеры в зависимости от типа отчета, но я могу создать только один и тот же маркер для всех координат. Карта

var map;
var infowindow = new google.maps.InfoWindow();

function initialization() {
    showAllReports();
}

function showAllReports() {
    $.ajax({
        url: 'HttpServlet',
        type: 'POST',
        data: { "tab_id": "1"},
        success: function(reports) {
            mapInitialization(reports);
        },
        error: function(xhr, status, error) {
            alert("An AJAX error occured: " + status + "\nError: " + error);
        }
    });
}

function mapInitialization(reports) {
    var mapOptions = {
        mapTypeId : google.maps.MapTypeId.ROADMAP, // Set the type of Map
    };

    // Render the map within the empty div
    map = new google.maps.Map(document.getElementById('map-canvas'),mapOptions);

    var bounds = new google.maps.LatLngBounds ();

    $.each(reports, function(i, e) {
        var long = Number(e['longitude']);
        var lat = Number(e['latitude']);
        var latlng = new google.maps.LatLng(lat, long);

        bounds.extend(latlng);

        // Create the infoWindow content
        var contentStr = '<h4>Report Details</h4><hr>';
        contentStr += '<p><b>' + 'Disaster' + ':</b>&nbsp' + e['disaster'] + '</p>';
        contentStr += '<p><b>' + 'Report Type' + ':</b>&nbsp' + e['report_type'] +
        '</p>';
        if (e['report_type'] == 'request' || e['report_type'] == 'donation') {
            contentStr += '<p><b>' + 'Resource Type' + ':</b>&nbsp' +
                e['resource_type'] + '</p>';
        }
        else if (e['report_type'] == 'damage') {
            contentStr += '<p><b>' + 'Damage Type' + ':</b>&nbsp' + e['damage_type']
            + '</p>';
        }
        contentStr += '<p><b>' + 'Reporter' + ':</b>&nbsp' +
        e['reporter_id'] + '</p>';

        contentStr += '<p><b>' + 'Timestamp' + ':</b>&nbsp' +
        e['time_stamp'].substring(0,19) + '</p>';
        if ('message' in e){
            contentStr += '<p><b>' + 'Message' + ':</b>&nbsp' + e['message'] + '</p>';
        }

        var icon = {
            url: 'https://1adn3cp4l2-flywheel.netdna-ssl.com/wp-content/uploads/2013/10/Donation-plugins-for-WordPress1.jpg', // url
            scaledSize: new google.maps.Size(40, 30), // scaled size
            origin: new google.maps.Point(0, 0), // origin
            anchor: new google.maps.Point(0, 0) // anchor
        };

        var marker = new google.maps.Marker({
            position: latlng,
            map: map,
            icon: icon,
            customInfo: contentStr,

        });


        // Add a Click Listener to the marker
        google.maps.event.addListener(marker, 'click', function() {
            // use 'customInfo' to customize infoWindow
            infowindow.setContent(marker['customInfo']);
            infowindow.open(map, marker); // Open InfoWindow
        });

    });

    map.fitBounds (bounds);

}


//Execute our 'initialization' function once the page has loaded.
google.maps.event.addDomListener(window, 'load', initialization);

1 Ответ

0 голосов
/ 19 ноября 2018

изменение изображения маркера icon на основе report_type.

ниже приведен пример того же.

var icon_img = '';

if(report_type === 'Donation') {
 icon_img = 'https://1adn3cp4l2-flywheel.netdna-ssl.com/wp-content/uploads/2013/10/Donation-plugins-for-WordPress1.jpg';
}else if(report_type === 'Disaster'){
  icon_img = 'Disaster.jpg';
}else if(report_type === 'damage'){
  icon_img = 'damage.jpg';
}


var icon = {
      url: icon_img, // url
      scaledSize: new google.maps.Size(40, 30), // scaled size
      origin: new google.maps.Point(0, 0), // origin
      anchor: new google.maps.Point(0, 0) // anchor
};
...