[英]How to change default marker in google map
我正在使用带有自动完成输入数据的谷歌地图,它有开始、中途停留和结束,我想更改谷歌地图的默认标记
我参考了这个帖子:
如果我使用地图的默认标记,它运行正常
我的 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 个点获取标记图像,如何解决问题
我在您的代码中遇到的错误是: 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 接口(根据文档),并将其移动到initMap
函数中。
一旦我解决了这个问题(并添加了缺少的必需 HTML...),我会收到更多 javascript 错误:
Uncaught ReferenceError: leg is not defined
这条线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
在同一行中Uncaught ReferenceError: map is not defined
,因为map
对initMap
函数是本地的。InvalidValueError: setPosition: not a LatLng or LatLngLiteral: not an Object
in the function: makeMarker(position, icon, title, map)
当它被调用时,因为leg.start_address
, leg.stopover_address
和leg.end_address
是addresses ,不是positions,那些应该是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);
// ...
}
代码片段:
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>
我能够通过使用以下代码来做到这一点:
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
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.