Google Maps API v3 - пользовательские маркеры направлений движения - PullRequest
2 голосов
/ 17 января 2012

Как бы я заменил маркеры направлений движения (а не маркеры карты) в google maps api v3?

Я не видел примеров этого нигде ...

enter image description here

Ответы [ 2 ]

4 голосов
/ 12 февраля 2012

У меня была такая же проблема.Подобно решению Джейсона использовать CSS, я использовал jQuery для ручной замены изображений значков на собственные изображения значков.Это позволяет мне использовать одно и то же изображение значка на картах и ​​в направлениях.Это также позволяет мне использовать обработчики щелчков, чтобы открывать одно и то же информационное окно при щелчке маркера на карте или на панели направлений.Я использую разные значки как для домашнего, так и для конечного местоположения, а также для маркеров путевых точек.Единственное раздражающее замечание было то, что мне нужно было использовать таймер JavaScript, чтобы подождать 1,5 секунды, чтобы я мог быть уверен, что направления закончили рендеринг, поскольку он асинхронный, и обратного вызова для этого нет.Изображения не могут быть заменены, пока они не добавлены в DOM.Вот мой код:

    function renderDrivingDirections(directionsResponse){
    var directionRenderOptions = {
            map: map,
            panel: directionsPanel,
            suppressInfoWindows: true,
            suppressMarkers: true
    };
    var directionsRenderer = new google.maps.DirectionsRenderer(directionRenderOptions);
    directionsRenderer.setDirections(directionsResponse);
    /* Replace the default map markers with custom ones for following reasons:
        1) Control over icon.  (Custom icons for start and finish)
        2) Control over icon color (to match the action status)
        3) Control infowindow that opens on marker click (Add Call/Action, add link to action details)
        However, we using the default rendering for the lines, and for text output of directions. So we need to wait 1.5 seconds after load 
    */
    window.setTimeout(    
            function(){
                showWaypointMarkers(directionsResponse);
                showOriginDestinationMarkers();
            },
            1500
    );
}

function showWaypointMarkers(directionsResponse) {
    var routeLegs = directionsResponse.routes[0].legs;
    var allImages = jQuery(directionsPanel).find("img");
    for (var i = 0, len = routeLegs.length -1; i < len; i++) {
        var iconUrl = "https://chart.googleapis.com/chart?chst=d_map_pin_letter_withshadow&chld=" + (i+1) + "|ffffff|000000";
        var marker = new google.maps.Marker({
            position: routeLegs[i+1].start_location,
            map: map,
            title: "Stop number: " + i,
            icon: {url: iconUrl}
        });
        var iconImageObj = jQuery("<img src='" + iconUrl + "'>");
        attachInfoWindow(marker, iconImageObj, i, routeLegs[i+1]);            
        allImages.eq(i+1).replaceWith(iconImageObj);
    }
}

function attachInfoWindow(marker, iconImageObj, legIndex, leg) {
    var infowindow = new google.maps.InfoWindow({
        content: "<div><h3>Stop Number: " + legIndex + "</h3><p>" + leg.start_address + "</p><a href='#'>(Stop Details)</a></div>"
    });
    google.maps.event.addListener(marker, 'click', function(){ //when the marker on map is clicked open info-window
        infowindow.open(map,marker);
    });
    iconImageObj.click(function(){ //when the marker on the driving directions is clicked, open info-window
        infowindow.open(map,marker);
    });
}
function showOriginDestinationMarkers(){ //here using same icon for first and last
    var iconUrl = "https://chart.googleapis.com/chart?chst=d_map_pin_icon_withshadow&chld=home|000000|FFFFFF"; //home icon
    new google.maps.Marker({ //add home location to map
        position: homeLocation,
        map: map, 
        title: messages.homeLocationTitle,
        icon: {url: iconUrl}
    });
    jQuery(directionsPanel, "img").first().replaceWith("<img src='" + iconUrl + "'>"); //replace their icon with ours
    jQuery(directionsPanel, "img").last().replaceWith("<img src='" + iconUrl + "'>"); //replace their icon with ours
}

Чтобы избежать использования таймера, мне нужно было бы разобрать направления и отобразить их самостоятельно.Информационные окна имеют собственный текст, основанный на путевой точке и ссылку на страницу сведений.

3 голосов
/ 17 января 2012

Иногда ключом является простота.

Я ответил на мой вопрос, используя css:

Строка A - это таблица:

<table id="adp-placemark" class="adp-placemark" jstcache="0">

и линия B:

<table class="adp-placemark" jstcache="0">

Таким образом, следующий css изменит маркеры:

#adp-placemark img, .adp-placemark img {
   display:none;
}
#adp-placemark {
   font-weight: bold;
   padding: 10px 10px 10px 30px;
   background: white url(../images/map_icons/number_1.png) no-repeat left center;
}
.adp-placemark {
   font-weight: bold;
   padding: 10px 10px 10px 30px;
   background: white url(../images/map_icons/number_2.png) no-repeat left center;
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...