谷歌Maps Api相当新。我有一个数据数组,我想循环遍历并在地图上绘制。看似相当简单,但我发现的所有多标记教程都相当复杂。
让我们以谷歌网站的数据数组为例:
var locations = [
['Bondi Beach', -33.890542, 151.274856, 4],
['Coogee Beach', -33.923036, 151.259052, 5],
['Cronulla Beach', -34.028249, 151.157507, 3],
['Manly Beach', -33.80010128657071, 151.28747820854187, 2],
['Maroubra Beach', -33.950198, 151.259302, 1]
];
我只是想绘制所有这些点,并在单击时弹出一个infoWindow来显示名称。
已接受的答案,在ES6中重写:
$(document).ready(() => {
const mapEl = $('#our_map').get(0); // OR document.getElementById('our_map');
// Display a map on the page
const map = new google.maps.Map(mapEl, { mapTypeId: 'roadmap' });
const buildings = [
{
title: 'London Eye, London',
coordinates: [51.503454, -0.119562],
info: 'carousel'
},
{
title: 'Palace of Westminster, London',
coordinates: [51.499633, -0.124755],
info: 'palace'
}
];
placeBuildingsOnMap(buildings, map);
});
const placeBuildingsOnMap = (buildings, map) => {
// Loop through our array of buildings & place each one on the map
const bounds = new google.maps.LatLngBounds();
buildings.forEach((building) => {
const position = { lat: building.coordinates[0], lng: building.coordinates[1] }
// Stretch our bounds to the newly found marker position
bounds.extend(position);
const marker = new google.maps.Marker({
position: position,
map: map,
title: building.title
});
const infoWindow = new google.maps.InfoWindow();
// Allow each marker to have an info window
google.maps.event.addListener(marker, 'click', () => {
infoWindow.setContent(building.info);
infoWindow.open(map, marker);
})
// Automatically center the map fitting all markers on the screen
map.fitBounds(bounds);
})
})
下面是一个Reactjs中多个标记的例子。
下面是映射组件
import React from 'react';
import PropTypes from 'prop-types';
import { Map, InfoWindow, Marker, GoogleApiWrapper } from 'google-maps-react';
const MapContainer = (props) => {
const [mapConfigurations, setMapConfigurations] = useState({
showingInfoWindow: false,
activeMarker: {},
selectedPlace: {}
});
var points = [
{ lat: 42.02, lng: -77.01 },
{ lat: 42.03, lng: -77.02 },
{ lat: 41.03, lng: -77.04 },
{ lat: 42.05, lng: -77.02 }
]
const onMarkerClick = (newProps, marker) => {};
if (!props.google) {
return <div>Loading...</div>;
}
return (
<div className="custom-map-container">
<Map
style={{
minWidth: '200px',
minHeight: '140px',
width: '100%',
height: '100%',
position: 'relative'
}}
initialCenter={{
lat: 42.39,
lng: -72.52
}}
google={props.google}
zoom={16}
>
{points.map(coordinates => (
<Marker
position={{ lat: coordinates.lat, lng: coordinates.lng }}
onClick={onMarkerClick}
icon={{
url: 'https://res.cloudinary.com/mybukka/image/upload/c_scale,r_50,w_30,h_30/v1580550858/yaiwq492u1lwuy2lb9ua.png',
anchor: new google.maps.Point(32, 32), // eslint-disable-line
scaledSize: new google.maps.Size(30, 30) // eslint-disable-line
}}
name={name}
/>))}
<InfoWindow
marker={mapConfigurations.activeMarker}
visible={mapConfigurations.showingInfoWindow}
>
<div>
<h1>{mapConfigurations.selectedPlace.name}</h1>
</div>
</InfoWindow>
</Map>
</div>
);
};
export default GoogleApiWrapper({
apiKey: process.env.GOOGLE_API_KEY,
v: '3'
})(MapContainer);
MapContainer.propTypes = {
google: PropTypes.shape({}).isRequired,
};
下面是一个几乎完整的示例javascript函数,它允许在JSONObject中定义多个标记。
它将只显示在地图边界内的标记。
这很重要,这样你就不用做额外的工作了。
你也可以设置一个标记的限制,这样你就不会显示一个极端数量的标记(如果有可能在你的使用);
如果地图中心的变化不超过500米,就不会显示标记。
这很重要,因为如果用户单击标记并在此过程中意外地拖动了地图,您不希望地图重新加载标记。
我将这个函数附加到地图的空闲事件侦听器,因此标记只在地图空闲时显示,并在不同的事件后重新显示标记。
活动屏幕截图
在信息窗口中显示更多内容的屏幕截图有一个小变化。
粘贴自pastbin.com
<script src=“//pastebin.com/embed_js/uWAbRxfg”></script>
已接受的答案,在ES6中重写:
$(document).ready(() => {
const mapEl = $('#our_map').get(0); // OR document.getElementById('our_map');
// Display a map on the page
const map = new google.maps.Map(mapEl, { mapTypeId: 'roadmap' });
const buildings = [
{
title: 'London Eye, London',
coordinates: [51.503454, -0.119562],
info: 'carousel'
},
{
title: 'Palace of Westminster, London',
coordinates: [51.499633, -0.124755],
info: 'palace'
}
];
placeBuildingsOnMap(buildings, map);
});
const placeBuildingsOnMap = (buildings, map) => {
// Loop through our array of buildings & place each one on the map
const bounds = new google.maps.LatLngBounds();
buildings.forEach((building) => {
const position = { lat: building.coordinates[0], lng: building.coordinates[1] }
// Stretch our bounds to the newly found marker position
bounds.extend(position);
const marker = new google.maps.Marker({
position: position,
map: map,
title: building.title
});
const infoWindow = new google.maps.InfoWindow();
// Allow each marker to have an info window
google.maps.event.addListener(marker, 'click', () => {
infoWindow.setContent(building.info);
infoWindow.open(map, marker);
})
// Automatically center the map fitting all markers on the screen
map.fitBounds(bounds);
})
})
根据Daniel Vassallo的回答,下面是一个以更简单的方式处理闭包问题的版本。
因为所有的标记都有一个单独的InfoWindow,而且JavaScript并不关心你是否给对象添加了额外的属性,你所需要做的就是给标记的属性添加一个InfoWindow,然后调用InfoWindow本身的.open() !
编辑:有了足够的数据,页面加载可能会花费很多时间,因此与其使用标记构造InfoWindow,不如只在需要时进行构造。注意,用于构造InfoWindow的任何数据都必须作为属性(data)追加到Marker。还要注意,在第一次单击事件之后,infoWindow将作为它的标记的属性持久化,因此浏览器不需要不断地重构。
var locations = [
['Bondi Beach', -33.890542, 151.274856, 4],
['Coogee Beach', -33.923036, 151.259052, 5],
['Cronulla Beach', -34.028249, 151.157507, 3],
['Manly Beach', -33.80010128657071, 151.28747820854187, 2],
['Maroubra Beach', -33.950198, 151.259302, 1]
];
var map = new google.maps.Map(document.getElementById('map'), {
center: new google.maps.LatLng(-33.92, 151.25)
});
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map,
data: {
name: locations[i][0]
}
});
marker.addListener('click', function() {
if(!this.infoWindow) {
this.infoWindow = new google.maps.InfoWindow({
content: this.data.name;
});
}
this.infoWindow.open(map,this);
})
}
异步版本:
<script type="text/javascript">
function initialize() {
var locations = [
['Bondi Beach', -33.890542, 151.274856, 4],
['Coogee Beach', -33.923036, 151.259052, 5],
['Cronulla Beach', -34.028249, 151.157507, 3],
['Manly Beach', -33.80010128657071, 151.28747820854187, 2],
['Maroubra Beach', -33.950198, 151.259302, 1]
];
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: new google.maps.LatLng(-33.92, 151.25),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
}
function loadScript() {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://maps.googleapis.com/maps/api/js?v=3.exp&' +
'callback=initialize';
document.body.appendChild(script);
}
window.onload = loadScript;
</script>