适当显示和重新加载自定义Google Maps标记

时间:2019-06-30 14:47:58

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

我不确定这是我做的事情还是需要解释的基础知识。基本上,我要做的是在单击按钮后刷新下面地图中的标记,这些标记包含在数组中(按钮元素ID为“ reloadMarkers”)

我在控制台中收到以下错误:   TypeError:无法读取未定义的属性“ length”     在setMarkers     在initMap

另外,我正在定义的标记实际上并未填充在地图上?

我认为这很简单,我做错了,但是我看不到任何其他类似的与自定义标记有关的问题,而且我对Google Maps API / javascript还是比较陌生,所以可能是我问题吗?

以下代码是我正在使用的代码:

<script id="mapMarkerPositions">

    var example = {
        info: '<strong>Shepherds Bush Market</strong><br>',
        lat: 51.502500,
        lng: -0.226495,
        type: 'info',
        label: {
            text: '£00.00',
            fontFamily: "Courier, Arial, Helvetica, sans-serif",
        }
    };

    var example2 = {
        info: '<strong>186 uxbridge</strong><br>',
        lat: 51.505333,
        lng: -0.225528,
        type: 'info',
        label: {
            text: '£00.00',
            fontFamily: "Courier, Arial, Helvetica, sans-serif",
        }
    };

    var map;
    var markers = [];
    var merchantMarkers = [
        [example.info, example.lat, example.lng, example.type, example.label, 1],
        [example2.info, example2.lat, example2.lng, example2.type, example2.label, 2]
    ];

    var icons = {
            icon: {
                path: ' M-240 -70 Q -240 -90 -220 -90 L -20 -90 Q 0 -90 0 -70 L 0 -20 Q 0 0 -20 0 L -220 0 Q -240 0 -240 -20 Z',
                fillColor: '#fff',
                fillOpacity: 1,
                scale: 0.3,
                strokeColor: '#555',
                strokeWeight: 2,
                labelOrigin: new google.maps.Point(-120, -46)
            }
        };
</script>

地图设置(紧接在上述脚本之后):

<script>

    function initMap() {

        var map = new google.maps.Map(document.getElementById('map'), {
            maxZoom: 20,
            minZoom: 14,
            zoom: 16,
            mapTypeControl: false,
            streetViewControl: false,
            center: {
                lat: 51.507388,
                lng: -0.127734
            }

        });

        setMarkers(merchantMarkers);

        document.getElementById('reloadMarkers').addEventListener('click', reloadMarkers);

        var infowindow = new google.maps.InfoWindow({})

        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(function(position) {
                initialLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
                map.setCenter(initialLocation);
            });
        }

    }
</script> 

设置标记:

<script>        

function setMarkers(locations) {

for (var i = 0; i < locations.length; i++) {
    var merchant = locations[i];
    var myLatLng = new google.maps.LatLng(merchant[1], merchant[2]);
    var marker = new google.maps.Marker({
        position: new google.maps.LatLng(merchant[i][1], merchant[i][2]),
                map: map,
                icon: icons.icon,
                label: merchant[i][4]
    })

    google.maps.event.addListener(
                marker,
                'click',
                (function(marker, i) {
                    return function() {
                        infowindow.setContent(locations[i][0])
                        infowindow.open(map, marker)
                    }
                })(marker, i)
            )
};

    markers.push(marker);
}

</script>

点击按钮即可重新加载标记的功能:

<script>

function reloadMarkers() {

// Loop through markers and set map to null for each
for (var i=0; i<markers.length; i++) {

    markers[i].setMap(null);
}

// Reset the markers array
markers = [];

// Call set markers to re-add markers
setMarkers(merchantMarkers);
}

</script>

最小示例:

#map {
			height: 400px
		}
<html>

<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0;">


</head>

<body>


	<script id="mapMarkerPositions">
		var example = {
			info: '<strong>Shepherds Bush Market</strong><br>',
			lat: 51.502500,
			lng: -0.226495,
			type: 'info',
			label: {
				text: '£00.00',
				fontFamily: "Courier, Arial, Helvetica, sans-serif",
			}
		};

		var example2 = {
			info: '<strong>186 uxbridge</strong><br>',
			lat: 51.505333,
			lng: -0.225528,
			type: 'info',
			label: {
				text: '£00.00',
				fontFamily: "Courier, Arial, Helvetica, sans-serif",
			}
		};

		var map;
		var markers = [];
		var merchantMarkers = [
			[example.info, example.lat, example.lng, example.type, example.label, 1],
			[example2.info, example2.lat, example2.lng, example2.type, example2.label, 2]
		];

		var icons = {
			icon: {
				path: ' M-240 -70 Q -240 -90 -220 -90 L -20 -90 Q 0 -90 0 -70 L 0 -20 Q 0 0 -20 0 L -220 0 Q -240 0 -240 -20 Z',
				fillColor: '#fff',
				fillOpacity: 1,
				scale: 0.3,
				strokeColor: '#555',
				strokeWeight: 2,
				labelOrigin: new google.maps.Point(-120, -46)
			}
		};
	</script>

	<script>
		function initMap() {

			var map = new google.maps.Map(document.getElementById('map'), {
				maxZoom: 20,
				minZoom: 14,
				zoom: 16,
				mapTypeControl: false,
				streetViewControl: false,
				center: {
					lat: 51.507388,
					lng: -0.127734
				}

			});

			setMarkers(merchantMarkers);

			document.getElementById('reloadMarkers').addEventListener('click', reloadMarkers);

			var infowindow = new google.maps.InfoWindow({})

			if (navigator.geolocation) {
				navigator.geolocation.getCurrentPosition(function(position) {
					initialLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
					map.setCenter(initialLocation);
				});
			}

		}
	</script>

	<script>
		function setMarkers(locations) {

			for (var i = 0; i < locations.length; i++) {
				var merchant = locations[i];
				var myLatLng = new google.maps.LatLng(merchant[1], merchant[2]);
				var marker = new google.maps.Marker({
					position: new google.maps.LatLng(merchant[i][1], merchant[i][2]),
					map: map,
					icon: icons.icon,
					label: merchant[i][4]
				})

				google.maps.event.addListener(
					marker,
					'click',
					(function(marker, i) {
						return function() {
							infowindow.setContent(locations[i][0])
							infowindow.open(map, marker)
						}
					})(marker, i)
				)
			};

			markers.push(marker);
		}
	</script>

	<script>
		function reloadMarkers() {

			// Loop through markers and set map to null for each
			for (var i = 0; i < markers.length; i++) {

				markers[i].setMap(null);
			}

			// Reset the markers array
			markers = [];

			// Call set markers to re-add markers
			setMarkers(merchantMarkers);
		}
	</script>

	<div id="map"></div>
	<input type="button" value="Reload markers" id="reloadMarkers">

	<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDBGFYRuVSrhZlIOuQn5BWhNNkggcssFFM&callback=initMap"></script>

</body>

</html>
		

1 个答案:

答案 0 :(得分:0)

问题:

    这行上的
  1. Uncaught ReferenceError: google is not definedlabelOrigin: new google.maps.Point(-120, -46)定义中的icons,该API在加载API之前运行。该代码必须在initMap函数内部,该函数在API加载后运行。

  2. Uncaught (in promise) TypeError: Cannot read property 'icon' of undefined由于上述错误。

  3. markers.push(marker);在错误的位置(它在创建标记的循环之外,因此仅适用于最后创建的标记)。将其移入循环。

screenshot of resulting map

工作代码段:

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

#map {
  height: 90%;
}
<script id="mapMarkerPositions">
  var example = {
    info: '<strong>Shepherds Bush Market</strong><br>',
    lat: 51.502500,
    lng: -0.226495,
    type: 'info',
    label: {
      text: '£00.00',
      fontFamily: "Courier, Arial, Helvetica, sans-serif",
    }
  };

  var example2 = {
    info: '<strong>186 uxbridge</strong><br>',
    lat: 51.505333,
    lng: -0.225528,
    type: 'info',
    label: {
      text: '£00.00',
      fontFamily: "Courier, Arial, Helvetica, sans-serif",
    }
  };

  var map;
  var markers = [];
  var merchantMarkers = [
    [example.info, example.lat, example.lng, example.type, example.label, 1],
    [example2.info, example2.lat, example2.lng, example2.type, example2.label, 2]
  ];

  var icons
</script>

<script>
  function initMap() {
    icons = {
      icon: {
        path: ' M-240 -70 Q -240 -90 -220 -90 L -20 -90 Q 0 -90 0 -70 L 0 -20 Q 0 0 -20 0 L -220 0 Q -240 0 -240 -20 Z',
        fillColor: '#fff',
        fillOpacity: 1,
        scale: 0.3,
        strokeColor: '#555',
        strokeWeight: 2,
        labelOrigin: new google.maps.Point(-120, -46)
      }
    };
    map = new google.maps.Map(document.getElementById('map'), {
      maxZoom: 20,
      minZoom: 14,
      zoom: 16,
      mapTypeControl: false,
      streetViewControl: false,
      center: {
        lat: 51.507388,
        lng: -0.127734
      }
    });

    setMarkers(merchantMarkers);

    document.getElementById('reloadMarkers').addEventListener('click', reloadMarkers);
    document.getElementById('centerOnMarkers').addEventListener('click', centerOnMarkers);
    var infowindow = new google.maps.InfoWindow({})

    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(function(position) {
        initialLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
        map.setCenter(initialLocation);
      });
    }

  }
</script>

<script>
  function setMarkers(locations) {

    for (var i = 0; i < locations.length; i++) {
      var merchant = locations[i];
      var myLatLng = new google.maps.LatLng(merchant[1], merchant[2]);
      var marker = new google.maps.Marker({
        position: myLatLng,
        map: map,
        icon: icons.icon,
        label: merchant[4]
      })

      google.maps.event.addListener(
        marker,
        'click',
        (function(marker, i) {
          return function() {
            infowindow.setContent(locations[i][0])
            infowindow.open(map, marker)
          }
        })(marker, i))
        markers.push(marker);
    };
  }
</script>

<script>
  function reloadMarkers() {

    // Loop through markers and set map to null for each
    for (var i = 0; i < markers.length; i++) {
      markers[i].setMap(null);
    }

    // Reset the markers array
    markers = [];

    // Call set markers to re-add markers
    setMarkers(merchantMarkers);
  }
</script>
<script>
  function centerOnMarkers() {
    var bounds = new google.maps.LatLngBounds();
    for (var i = 0; i < markers.length; i++) {
      bounds.extend(markers[i].getPosition());
    }
    map.fitBounds(bounds);
  }
</script>
<div id="map"></div>
<input type="button" value="Reload markers" id="reloadMarkers" />
<input type="button" id="centerOnMarkers" value="center on markers" />

<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap"></script>