【问题标题】:How to change default marker in google map如何更改谷歌地图中的默认标记
【发布时间】:2020-09-12 09:35:00
【问题描述】:

我正在使用带有自动完成输入数据的谷歌地图,它有开始、中途停留和结束,我想更改谷歌地图的默认标记

我已经参考了这篇文章:

Change individual markers in google maps directions

如果我使用地图的默认标记,它运行正常

我的 HTML:

<div id="map_canvas"></div>

我的脚本:

                    <script>                    
                        function initMap() {
                              var map = new google.maps.Map(document.getElementById('map_canvas'), {
                                mapTypeControl: false,
                                center: {
                                    lat: 16.318031, 
                                    lng: 107.432559
                                },
                                zoom: 5                                 
                              });
                              new AutocompleteDirectionsHandler(map);
                            }
                            
                            function AutocompleteDirectionsHandler(map) {
                              this.map = map;
                              this.originPlaceId = null;
                              this.destinationPlaceId = null;
                              this.destinationPlaceId2 = null;
                              this.travelMode = 'DRIVING';
                            
                              var originInput = document.getElementById('start');
                              var destinationInput = document.getElementById('waypoints');
                              var destinationInput2 = document.getElementById('end');
                            
                              var modeSelector = document.getElementById('mode-selector');
                            
                              this.directionsService = new google.maps.DirectionsService;
                              this.directionsDisplay = new google.maps.DirectionsRenderer;
                              this.directionsDisplay.setMap(map);
                            
                              var originAutocomplete = new google.maps.places.Autocomplete(originInput, {placeIdOnly: true});
                              var destinationAutocomplete2 = new google.maps.places.Autocomplete(destinationInput, {placeIdOnly: true});
                              var destinationAutocomplete = new google.maps.places.Autocomplete(destinationInput2, {placeIdOnly: true});                                
                            
                              this.setupPlaceChangedListener(originAutocomplete, 'ORIG');
                              this.setupPlaceChangedListener(destinationAutocomplete, 'DEST');
                              this.setupPlaceChangedListener(destinationAutocomplete2, 'DEST2');
                            }
                            
                            AutocompleteDirectionsHandler.prototype.setupClickListener = function(id, mode) {
                              var radioButton = document.getElementById(id);
                              var me = this;
                              radioButton.addEventListener('click', function() {
                                me.travelMode = mode;
                                me.route();
                              });
                            };
                            
                            AutocompleteDirectionsHandler.prototype.setupPlaceChangedListener = function(autocomplete, mode) {
                              var me = this;
                              autocomplete.bindTo('bounds', this.map);
                              autocomplete.addListener('place_changed', function() {
                                var place = autocomplete.getPlace();
                                if (!place.place_id) {
                                  window.alert("please input content.");
                                  return;
                                }
                                if (mode === 'ORIG') {
                                  me.originPlaceId = place.place_id;
                                } else if (mode === 'DEST') {
                                  me.destinationPlaceId = place.place_id;
                                } else if (mode === 'DEST2') {
                                  me.destinationPlaceId2 = place.place_id;
                                }
                                me.route();
                              });
                            };
                            
                            AutocompleteDirectionsHandler.prototype.route = function() {
                            
                              console.log("originPlaceId=" + this.originPlaceId + " destinationPlaceId=" + this.destinationPlaceId + " destinationPlaceId2=" + this.destinationPlaceId2);
                            
                              if (!this.originPlaceId || !this.destinationPlaceId) {
                                return;
                              }
                              var me = this;
                            
                              var waypts = [];
                              if (!!this.destinationPlaceId2) {
                                waypts.push({
                                  location: {
                                    'placeId': this.destinationPlaceId2
                                  },
                                  stopover: true
                                });
                              }
                            
                              this.directionsService.route({
                                origin: {
                                  'placeId': this.originPlaceId
                                },
                                destination: {
                                  'placeId': this.destinationPlaceId
                                },
                                waypoints: waypts,
                                optimizeWaypoints: true,
                                travelMode: this.travelMode
                              }, function(response, status) {
                                if (status === 'OK') {
                                  me.directionsDisplay.setDirections(response);
                                  var route = response.routes[0];
                                  var summaryPanel = document.getElementById("directions-panel");
                            
                               // For each route, display summary information.
                                  summaryPanel.innerHTML = ""; 
                            
                                  // For each route, display summary information.
                                  for (var i = 0; i < route.legs.length; i++) {
                                      
                                    makeMarker(leg.start_address, icons.start, "title", map);
                                    makeMarker(leg.stopover_address, icons.end, 'title', map);
                                    makeMarker(leg.end_address, icons.end, 'title', map);
                            
                                    var routeSegment = i + 1;
                                    summaryPanel.innerHTML +=
                                      "<b>Point:  " + routeSegment + "</b><br> Start: ";
                                    summaryPanel.innerHTML += route.legs[i].start_address + " </b><br> end: ";
                                    summaryPanel.innerHTML += route.legs[i].end_address + "<br>";
                                    summaryPanel.innerHTML += route.legs[i].distance.text + "<br><br>";
                                  }
                                  
                                  computeTotalDistance(response);
                                } 
                                
                                else {
                                    window.alert('error somewhere. ' + status);
                                }
                              });
                            };
                            
                            function makeMarker(position, icon, title, map) {
                                new google.maps.Marker({
                                    position: position,
                                    map: map,
                                    icon: icon,
                                    title: title
                                });
                            }

                            var icons = {
                                
                                start: new google.maps.MarkerImage(
                                // URL
                                'http://maps.google.com/mapfiles/ms/micons/blue.png',
                                // (width,height)
                                new google.maps.Size(44, 32),
                                // The origin point (x,y)
                                new google.maps.Point(0, 0),
                                // The anchor point (x,y)
                                new google.maps.Point(22, 32)),
                                
                                stopover: new google.maps.MarkerImage(
                                // URL
                                'http://maps.google.com/mapfiles/ms/micons/yellow.png',
                                // (width,height)
                                new google.maps.Size(44, 32),
                                // The origin point (x,y)
                                new google.maps.Point(0, 0),
                                // The anchor point (x,y)
                                new google.maps.Point(22, 32)),
                                
                                end: new google.maps.MarkerImage(
                                // URL
                                'http://maps.google.com/mapfiles/ms/micons/green.png',
                                // (width,height)
                                new google.maps.Size(44, 32),
                                // The origin point (x,y)
                                new google.maps.Point(0, 0),
                                // The anchor point (x,y)
                                new google.maps.Point(22, 32))
                            };

                            function computeTotalDistance(result) {
                                  var totalDist = 0;
                                  var totalTime = 0;
                                  var myroute = result.routes[0];
                                  for (i = 0; i < myroute.legs.length; i++) {
                                    totalDist += myroute.legs[i].distance.value;
                                    totalTime += myroute.legs[i].duration.value;
                                  }
                                  totalDist = totalDist / 1000.
                                  document.getElementById("total").innerHTML = "Total km: " + totalDist + " km<br>Total: " + (totalTime / 60).toFixed(2) + " min";
                            }
                            
                            initMap();  
                    </script>       

当我更改另一个标记图像时,它无法从 3 个点获取标记图像,如何解决问题

【问题讨论】:

  • 请提供一个 minimal reproducible example 来证明您的问题,包括所有必需的 HTML/CSS。
  • @geocodezip: 是的,我已经参考了你的来源,你能指导我解决问题吗
  • 您缺少很多必需的 HTML,并且您没有提供任何必需的 CSS。

标签: javascript google-maps google-maps-api-3


【解决方案1】:

您的代码出现的错误是:Uncaught ReferenceError: google is not defined,因为icons 的定义在initMap 函数之外,但取决于 Google Maps Javascript API v3。

注意: MarkerImage 已在 很久 之前 (v3.10) 被弃用,请参阅:https://developers.google.com/maps/documentation/javascript/markers#convertingtoicon

将其更改为 MarkerIcon 接口(根据 the documentation),并将其移至 initMap 函数内。

一旦我解决了这个问题(并添加了缺少的所需 HTML...),我会收到更多的 javascript 错误:

  • Uncaught ReferenceError: leg is not defined 在这一行:makeMarker(leg.start_address, icons.start, "title", map);(因为缺少var leg = route.legs[i]; 的分配)
  • Uncaught ReferenceError: map is not defined 在同一行,因为 map 是 initMap 函数的本地函数。
  • 函数中的InvalidValueError: setPosition: not a LatLng or LatLngLiteral: not an Object:makeMarker(position, icon, title, map) 被调用时,因为leg.start_address、leg.stopover_address 和leg.end_address 是地址,而不是位置,应该是start_location、end_location(没有 leg.stopover_location 或 leg.stopover_address 这样的东西;您必须处理结果以确定哪些应该是“中途停留”图标)。
for (var i = 0; i < route.legs.length; i++) {
  var leg = route.legs[i];
  if (i === 0)
    makeMarker(leg.start_location, icons.start, "title", map);
  if (i === (route.legs.length - 1))
    makeMarker(leg.end_location, icons.end, 'title', map);
  else
    makeMarker(leg.end_location, icons.stopover, 'title', map);
  // ...
}

proof of concept fiddle

代码 sn-p:

var icons;
var map;
var markers = [];

function initMap() {
  map = new google.maps.Map(document.getElementById('map_canvas'), {
    mapTypeControl: false,
    center: {
      lat: 16.318031,
      lng: 107.432559
    },
    zoom: 5
  });
  icons = {
    start: {
      // URL
      url: 'http://maps.google.com/mapfiles/ms/micons/blue.png',
      // (width,height)
      size: new google.maps.Size(32, 32),
      // The origin point (x,y)
      origin: new google.maps.Point(0, 0),
      // The anchor point (x,y)
      anchor: new google.maps.Point(16, 32)
    },

    stopover: {
      // URL
      url: 'http://maps.google.com/mapfiles/ms/micons/yellow.png',
      // (width,height)
      size: new google.maps.Size(32, 32),
      // The origin point (x,y)
      origin: new google.maps.Point(0, 0),
      // The anchor point (x,y)
      anchor: new google.maps.Point(16, 32)
    },

    end: {
      // URL
      url: 'http://maps.google.com/mapfiles/ms/micons/green.png',
      // (width,height)
      size: new google.maps.Size(32, 32),
      // The origin point (x,y)
      origin: new google.maps.Point(0, 0),
      // The anchor point (x,y)
      anchor: new google.maps.Point(16, 32)
    }
  };

  new AutocompleteDirectionsHandler(map);
}

function AutocompleteDirectionsHandler(map) {
  this.map = map;
  this.originPlaceId = null;
  this.destinationPlaceId = null;
  this.destinationPlaceId2 = null;
  this.travelMode = 'DRIVING';

  var originInput = document.getElementById('start');
  var destinationInput = document.getElementById('waypoints');
  var destinationInput2 = document.getElementById('end');

  var modeSelector = document.getElementById('mode-selector');

  this.directionsService = new google.maps.DirectionsService();
  this.directionsDisplay = new google.maps.DirectionsRenderer({
    suppressMarkers: true
  });
  this.directionsDisplay.setMap(map);

  var originAutocomplete = new google.maps.places.Autocomplete(originInput, {
    fields: ['place_id']
  });
  var destinationAutocomplete2 = new google.maps.places.Autocomplete(destinationInput, {
    fields: ['place_id']
  });
  var destinationAutocomplete = new google.maps.places.Autocomplete(destinationInput2, {
    fields: ['place_id']
  });

  this.setupPlaceChangedListener(originAutocomplete, 'ORIG');
  this.setupPlaceChangedListener(destinationAutocomplete, 'DEST');
  this.setupPlaceChangedListener(destinationAutocomplete2, 'DEST2');
}

AutocompleteDirectionsHandler.prototype.setupClickListener = function(id, mode) {
  var radioButton = document.getElementById(id);
  var me = this;
  radioButton.addEventListener('click', function() {
    me.travelMode = mode;
    me.route();
  });
};

AutocompleteDirectionsHandler.prototype.setupPlaceChangedListener = function(autocomplete, mode) {
  var me = this;
  autocomplete.bindTo('bounds', this.map);
  autocomplete.addListener('place_changed', function() {
    var place = autocomplete.getPlace();
    if (!place.place_id) {
      window.alert("please input content.");
      return;
    }
    if (mode === 'ORIG') {
      me.originPlaceId = place.place_id;
    } else if (mode === 'DEST') {
      me.destinationPlaceId = place.place_id;
    } else if (mode === 'DEST2') {
      me.destinationPlaceId2 = place.place_id;
    }
    me.route();
  });
};

AutocompleteDirectionsHandler.prototype.route = function() {
  for (var i = 0; i < markers.length; i++) {
    markers[i].setMap(null);
  }
  markers = [];
  console.log("originPlaceId=" + this.originPlaceId + " destinationPlaceId=" + this.destinationPlaceId + " destinationPlaceId2=" + this.destinationPlaceId2);

  if (!this.originPlaceId || !this.destinationPlaceId) {
    return;
  }
  var me = this;

  var waypts = [];
  if (!!this.destinationPlaceId2) {
    waypts.push({
      location: {
        'placeId': this.destinationPlaceId2
      },
      stopover: true
    });
  }

  this.directionsService.route({
    origin: {
      'placeId': this.originPlaceId
    },
    destination: {
      'placeId': this.destinationPlaceId
    },
    waypoints: waypts,
    optimizeWaypoints: true,
    travelMode: this.travelMode
  }, function(response, status) {
    if (status === 'OK') {
      me.directionsDisplay.setDirections(response);
      var route = response.routes[0];
      var summaryPanel = document.getElementById("directions-panel");

      // For each route, display summary information.
      summaryPanel.innerHTML = "";

      // For each route, display summary information.
      for (var i = 0; i < route.legs.length; i++) {
        var leg = route.legs[i];
        if (i === 0)
          makeMarker(leg.start_location, icons.start, "title", map);
        if (i === (route.legs.length - 1))
          makeMarker(leg.end_location, icons.end, 'title', map);
        else
          makeMarker(leg.end_location, icons.stopover, 'title', map);
        var routeSegment = i + 1;
        summaryPanel.innerHTML +=
          "<b>Point:  " + routeSegment + "</b><br> Start: ";
        summaryPanel.innerHTML += route.legs[i].start_address + " </b><br> end: ";
        summaryPanel.innerHTML += route.legs[i].end_address + "<br>";
        summaryPanel.innerHTML += route.legs[i].distance.text + "<br><br>";
      }

      computeTotalDistance(response);
    } else {
      window.alert('error somewhere. ' + status);
    }
  });
};

function makeMarker(position, icon, title, map) {
  var marker = new google.maps.Marker({
    position: position,
    map: map,
    icon: icon,
    title: title
  });
  markers.push(marker);
}


function computeTotalDistance(result) {
  var totalDist = 0;
  var totalTime = 0;
  var myroute = result.routes[0];
  for (i = 0; i < myroute.legs.length; i++) {
    totalDist += myroute.legs[i].distance.value;
    totalTime += myroute.legs[i].duration.value;
  }
  totalDist = totalDist / 1000.
  document.getElementById("total").innerHTML = "Total km: " + totalDist + " km<br>Total: " + (totalTime / 60).toFixed(2) + " min";
}
/* Always set the map height explicitly to define the size of the div
 * element that contains the map. */

#map_canvas {
  height: 60%;
}


/* Optional: Makes the sample page fill the window. */

html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}

.controls {
  margin-top: 10px;
  border: 1px solid transparent;
  border-radius: 2px 0 0 2px;
  box-sizing: border-box;
  -moz-box-sizing: border-box;
  height: 32px;
  outline: none;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
}

#origin-input,
#destination-input {
  background-color: #fff;
  font-family: Roboto;
  font-size: 15px;
  font-weight: 300;
  margin-left: 12px;
  padding: 0 11px 0 13px;
  text-overflow: ellipsis;
  width: 200px;
}

#origin-input:focus,
#destination-input:focus {
  border-color: #4d90fe;
}

#mode-selector {
  color: #fff;
  background-color: #4d90fe;
  margin-left: 12px;
  padding: 5px 11px 0px 11px;
}

#mode-selector label {
  font-family: Roboto;
  font-size: 13px;
  font-weight: 300;
}
<!DOCTYPE html>
<html>

<head>
  <title>Place Autocomplete and Directions</title>
  <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
  <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap&libraries=places&v=weekly" defer></script>
  <!-- jsFiddle will insert css and js -->
</head>

<body>
  <div>
    <input id="start" class="controls" type="text" placeholder="Enter an origin location" value="New York, NY">

    <input id="end" class="controls" type="text" placeholder="Enter a destination location" value="Philadelphia, PA">

    <input id="waypoints" class="controls" type="text" placeholder="Enter a destination location" value="Newark, NJ">

    <div id="mode-selector" class="controls" style="display:none">
      <input type="radio" name="type" id="changemode-walking" checked="checked">
      <label for="changemode-walking">Walking</label>

      <input type="radio" name="type" id="changemode-transit">
      <label for="changemode-transit">Transit</label>

      <input type="radio" name="type" id="changemode-driving">
      <label for="changemode-driving">Driving</label>

    </div>
  </div>

  <div id="total"></div>
  <div id="map_canvas"></div>
  <div id="directions-panel"></div>
</body>

</html>

【讨论】:

  • 嗨@geocodezip,我知道了,但似乎有问题,如果您更改任何位置的名称,旧位置不清楚,它会在地图上创建旧标记和新标记,你能尝试对此进行测试
  • 见:Google Map API - Removing Markers。更新了代码 sn-p 和 fiddle 来解决。
【解决方案2】:

我可以通过使用此代码来做到这一点:

let image = 'map_icon_marker.ico'; //put the source to your marker here

let marker = new google.maps.Marker({
    position: intersection_one, //the position you want
    map: map,
    icon: image
  });

【讨论】:

  • 您可以将图像定义为常量,因为您不会更改它
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-06-11
  • 2014-09-26
  • 2015-03-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-07
相关资源
最近更新 更多