Google maps Значок маркера обводкиВес динамически увеличивается, чтобы показать предупреждение - PullRequest
0 голосов
/ 07 апреля 2019

Я пытаюсь создать значок маркера карты Google, который отображается как предупреждение для определенного маркера.План состоит в том, чтобы увеличивать штрих-вес значка и динамически после загрузки карты.

Моя мысль для предупреждения: увеличьте ударный вес внешнего «красного» с 1 до 30 и перезапустите с 1 до 30,таким образом, это похоже на предупреждение о красном значке.

Ref: Google maps Заполнение значков маркера между icon-fillColor и strokeColor

Мой код маркера:

// Loop through our array of markers & place each one on the map  
for (i = 0; i < markers.length; i++) {
    if (i % 2) {
        color = "red";
    } else {
        color = "green";
    }
    var position = new google.maps.LatLng(markers[i][1], markers[i][2]);
    bounds.extend(position);

    var fillColor = "#4A86FE";
    var stripeColor = "white";
    var outsideColor = color;
    var title = "My Title";
    var id = i;
    var label = {
        text: '' + i + '',
        color: "white",
        fontWeight: 'bold',
        fontSize: '16px',
    };
    var marker = new google.maps.Marker({
        zIndex: 10, // bottom
        id: id,
        position: position,
        map: map,
        title: title,
        icon: {
            path: google.maps.SymbolPath.CIRCLE,
            scale: 15,
            fillColor: fillColor,
            fillOpacity: 1.0,
            strokeWeight: 6,
            strokeOpacity: 0.8,
            strokeColor: outsideColor,
            rotation: 30
        },
    });

    var marker = new google.maps.Marker({
        zIndex: 15, // top
        id: id,
        position: position,
        label: label,
        map: map,
        title: title,
        icon: {
            path: google.maps.SymbolPath.CIRCLE,
            scale: 15,
            fillColor: fillColor,
            fillOpacity: 1.0,
            strokeWeight: 2,
            strokeOpacity: 0.8,
            strokeColor: stripeColor,
            rotation: 30
        },
    });


    // To Bounce the selected Marker
    //if(color == "red"){
    //  marker.setAnimation(google.maps.Animation.BOUNCE);
    //}
    // Marker Zoom on Click

    // Automatically center the map fitting all markers on the screen
    map.fitBounds(bounds);
}

google.maps.event.addDomListener(window, 'load', initialize);

Попробуйте 1: триггер сработал: (

      (function (i,marker){
            google.maps.event.addListener(marker, 'click' , function() {
                var icon = this.getIcon();
              icon.strokeWeight = i;
              this.setIcon(icon);
            });
        });(i, marker);
      document.getElementById(marker).click();

Попробуйте 2: Это работает, но для последнего маркера в цикле

// To Bounce the selected Marker
                if(color == "red"){
                  setInterval(function() {
                     if(on) {
                       marker.setMap(null);
                     } else {
                       var icon = marker.getIcon();
                       icon.strokeWeight = 10;
                       marker.setIcon(icon);
                       marker.setMap(map);
                     }
                    on = !on;
                  }, intervalSeconds * 1000);
                  //marker.setAnimation(google.maps.Animation.BOUNCE);
                }

Попробуйте 3: Это плохоодин: (

marker.addListener('click', function() {
            var icon = this.getIcon();
            var self = this;
            j = 0;
            console.log('im clicked');
            for (i = 1; i < 20; i++) {
                icon.strokeWeight = i;
                window.setTimeout(function() {
                    self.setIcon(icon);
                }, 3000);

                console.log(i);
                if (i == 19) {
                    i = 0;
                    j++
                }
                if (j == 10) {
                    break;
                }
            }

Попытка достичь чего-то вроде следующего:

enter image description here

1 Ответ

1 голос
/ 07 апреля 2019

Я бы предложил создать третий маркер, который выполняет функцию "оповещения", поместите его под двумя другими и измените его штрих-вес, чтобы дать "пульсацию":

function alertMarker(map, latLng, color) {
  var intervalSeconds = 0.025;
  var direction = 1;
  var strokeWeight = 10;
  var maxStrokeWeight = 30;
  var alertMark = new google.maps.Marker({
    position: latLng,
    map: map,
    zIndex: 5, // very bottom
    icon: {
      path: google.maps.SymbolPath.CIRCLE,
      scale: 15,
      fillColor: color,
      fillOpacity: 1.0,
      strokeWeight: 6,
      strokeOpacity: 0.8,
      strokeColor: color,
      rotation: 30
    },
  })
  setInterval(function() {
      if (((direction>0) && strokeWeight <maxStrokeWeight)||((direction<0) && strokeWeight>10)) {
        strokeWeight+=direction;
      } else if (strokeWeight==10) {
        direction=1;
      } else if (strokeWeight==maxStrokeWeight) {
        direction=-1;
      }
      var icon = alertMark.getIcon();
      icon.strokeWeight = strokeWeight;
      icon.strokeOpacity = 0.6
      alertMark.setIcon(icon);
    }, intervalSeconds * 1000);
    return alertMark;
}

подтверждение концепции скрипки

Примечание: это просто подтверждение концепции, если вы ожидаете, что это будет долгосрочная функциональность, вы захотите сохранить дескрипторы функций таймера и отменить их, а не оставлять их все запущенными на заднем плане скрытые маркеры

screenshot of resulting map

фрагмент кода:

function initMap() {
  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 4,
    center: {
      lat: -25.363882,
      lng: 131.044922
    }
  });

  var position = map.getCenter(),
    i = 10;
  var mark1 = makeComplexIcon(map, position, "#4A86FE", "white", "red", "My Title", i, {
    text: 'id',
    color: "white",
    fontWeight: 'bold',
    fontSize: '16px',
  });
  var aM = alertMarker(map, mark1.getPosition(), "red");
  var mark2 = makeComplexIcon(map, {
    lat: -27.6728168,
    lng: 121.6283098
  }, "green", "yellow", "orange", "W. Australia", 12, {
    text: 'id1',
    color: "blue",
    fontWeight: 'bold',
    fontSize: '16px',
  })
  var mark3 = makeComplexIcon(map, {
    lat: -30.0,
    lng: 136.2
  }, "black", "white", "black", "S. Australia", 14, {
    text: 'id2',
    color: "red",
    fontWeight: 'bold',
    fontSize: '16px',
  });
  setTimeout(function() {
    aM.setMap(null);
    aM = alertMarker(map, mark2.getPosition(), "orange")
  }, 5000)
  setTimeout(function() {
    aM.setMap(null);
    aM = alertMarker(map, mark3.getPosition(), "black")
  }, 10000)
  setTimeout(function() {
    aM.setMap(null);
    alertMarker(map, mark1.getPosition(), "red")
  }, 15000)
}

function makeComplexIcon(map, latLng, fillColor, stripeColor, outsideColor, title, id, label) {
  var bottom = new google.maps.Marker({
    zIndex: 10, // bottom
    id: id,
    position: latLng,
    map: map,
    title: title,
    icon: {
      path: google.maps.SymbolPath.CIRCLE,
      scale: 15,
      fillColor: fillColor,
      fillOpacity: 1.0,
      strokeWeight: 6,
      strokeOpacity: 0.8,
      strokeColor: outsideColor,
      rotation: 30
    },
  });
  var top = new google.maps.Marker({
    zIndex: 15, // top
    id: id,
    position: latLng,
    label: label,
    map: map,
    title: title,
    icon: {
      path: google.maps.SymbolPath.CIRCLE,
      scale: 15,
      fillColor: fillColor,
      fillOpacity: 1.0,
      strokeWeight: 2,
      strokeOpacity: 0.8,
      strokeColor: stripeColor,
      rotation: 30
    },
  });
  return bottom;
}

function alertMarker(map, latLng, color) {
  var intervalSeconds = 0.025;
  var direction = 1;
  var strokeWeight = 10;
  var maxStrokeWeight = 30;
  var alertMark = new google.maps.Marker({
    position: latLng,
    map: map,
    zIndex: 5, // very bottom
    icon: {
      path: google.maps.SymbolPath.CIRCLE,
      scale: 15,
      fillColor: color,
      fillOpacity: 1.0,
      strokeWeight: 6,
      strokeOpacity: 0.8,
      strokeColor: color,
      rotation: 30
    },
  })
  setInterval(function() {
    if (((direction > 0) && strokeWeight < maxStrokeWeight) || ((direction < 0) && strokeWeight > 10)) {
      strokeWeight += direction;
    } else if (strokeWeight == 10) {
      direction = 1;
    } else if (strokeWeight == maxStrokeWeight) {
      direction = -1;
    }
    var icon = alertMark.getIcon();
    icon.strokeWeight = strokeWeight;
    icon.strokeOpacity = 0.6
    alertMark.setIcon(icon);
  }, intervalSeconds * 1000);
  return alertMark;
}
html,
body,
#map {
  height: 100%;
  margin: 0;
  padding: 0;
}
<div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap"></script>
...