【问题标题】:Presenting and Reloading Custom Google Maps Markers Appropriately适当地展示和重新加载自定义谷歌地图标记
【发布时间】:2019-11-11 12:36:29
【问题描述】:

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

我在控制台中收到以下错误: TypeError:无法读取未定义的属性“长度” 在 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>
		

【问题讨论】:

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


    【解决方案1】:

    问题:

    1. Uncaught ReferenceError: google is not defined 在这一行:labelOrigin: new google.maps.Point(-120, -46)icons 的定义中,它在 API 加载之前运行。这需要在 API 加载后运行的 initMap 函数内部。

    2. Uncaught (in promise) TypeError: Cannot read property 'icon' of undefined 因为上面的错误。

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

    工作代码 sn-p:

    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>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-04
      • 2016-03-28
      • 2013-08-21
      • 1970-01-01
      • 2012-09-05
      • 2015-10-07
      相关资源
      最近更新 更多