我有一个谷歌地图,它在整个曼哈顿市丢了很多别针。为了更好地组织这种幽闭恐惧症的大头针,我想提供一个缩小的视图,将曼哈顿划分为清晰划定的社区,您可以单击它们,然后放大并显示该社区区域中的各个大头针。这是我想要实现的示例:
我不知道从哪里开始。我已经阅读了谷歌地图文档,但我仍然不确定(a)我应该用来绘制边界的 javascript 方法,以及(b)我可以在哪里获得有关如何绘制曼哈顿社区边界的有意义的信息。
有人有这方面的经验吗?
我有一个谷歌地图,它在整个曼哈顿市丢了很多别针。为了更好地组织这种幽闭恐惧症的大头针,我想提供一个缩小的视图,将曼哈顿划分为清晰划定的社区,您可以单击它们,然后放大并显示该社区区域中的各个大头针。这是我想要实现的示例:
我不知道从哪里开始。我已经阅读了谷歌地图文档,但我仍然不确定(a)我应该用来绘制边界的 javascript 方法,以及(b)我可以在哪里获得有关如何绘制曼哈顿社区边界的有意义的信息。
有人有这方面的经验吗?
幸运的是,我找到了一个站点,您可以在其中以 GeoJson 格式获得有关社区边界的重要信息。听说过“社区项目”吗?在这里http://zetashapes.com/editor/36061我搜索了“Manhattan”并找到了那个页面。他们也有许多其他城市社区。您会注意到,那里有一个按钮可以将 GeoJson 数据下载为 .json 文件。现在,我觉得作为网站管理员和开发人员,我们有责任确保用户不需要下载不必要的数据,并减少我们的带宽需求,我发现 GeoJson 对于我们需要从中获得的东西来说过于臃肿和过大。因此,第一件事是在您的服务器或本地主机上创建一个 .php 文件并将其命名为“reduce.php”或您想要的任何名称,
<?php
$jsonString = file_get_contents('36061.json');
$obj = json_decode($jsonString);
$arr = array();
foreach($obj->features as $feature) {
echo $feature->properties->label.'<br>';//just to let you see all the neighborhood names
array_push($arr, array($feature->properties->label, $feature->geometry->coordinates));
}
file_put_contents('36061_minimal.json', json_encode($arr));
?>
然后将“36061.json”文件放在与上述php文件相同的目录下,然后在浏览器中查看运行该php文件,它将创建一个大约一半大小的“36061_minimal.json”文件。好的,现在已经处理好了,对于下面的示例,您将需要以下 javascript 文件,其中有一个 NeighborhoodGroup 构造函数,用于跟踪我们不同的社区。关于它的最重要的事情是你应该实例化一个 NeighborhoodGroup 的新实例,然后通过调用它的 addNeighborhood(name, polygon) 方法向它添加社区,你提供一个名称和一个 google.maps.Polygon 实例,然后您可以通过调用 addMarker(marker) 方法并为其提供 google.maps.Marker 对象来将标记对象添加到您的社区组,如果可能,标记将被委托给适当的邻域,否则如果标记不适合我们的任何邻域,addMarker 将返回 false。因此,将以下文件命名为“NeighborhoodGroup.js”:
//NeighborhoodGroup.js
//requires that the google maps geometry library be loaded
//via a "libraries=geometry" parameter on the url to the google maps script
function NeighborhoodGroup(name) {
this.name = name;
this.hoods = [];
//enables toggling markers on/off between different neighborhoods if set to true
this.toggleBetweenHoods = false;
//enables panning and zooming to fit the particular neighborhood in the viewport
this.fitHoodInViewport = true;
this.selectedHood = null;
this.lastSelectedHood = null;
}
NeighborhoodGroup.prototype.getHood = function (name) {
for (var i = 0, len = this.hoods.length; i < len; i++) {
if (this.hoods[i].name == name) {
return this.hoods[i];
}
}
return null;
};
NeighborhoodGroup.prototype.addNeighborhood = function (name, polygon) {
var O = this,
hood = new Neighborhood(name, polygon);
O.hoods.push(hood);
google.maps.event.addListener(polygon, 'click', function () {
if (O.toggleBetweenHoods) {
O.lastSelectedHood = O.selectedHood;
O.selectedHood = hood;
if (O.lastSelectedHood !== null && O.lastSelectedHood.name != name) {
O.lastSelectedHood.setMarkersVisible(false);
}
}
hood.setMarkersVisible(!hood.markersVisible);
if (O.fitHoodInViewport) {
hood.zoomTo();
}
});
};
//marker must be a google.maps.Marker object
//addMarker will return true if the marker fits within one
//of this NeighborhoodGroup object's neighborhoods, and
//false if the marker does not fit any of our neighborhoods
NeighborhoodGroup.prototype.addMarker = function (marker) {
var bool,
i = 0,
len = this.hoods.length;
for (; i < len; i++) {
bool = this.hoods[i].addMarker(marker);
if (bool) {
return bool;
}
}
return bool;
};
//the Neighborhood constructor is not intended to be called
//by you, is only intended to be called by NeighborhoodGroup.
//likewise for all of it's prototype methods, except for zoomTo
function Neighborhood(name, polygon) {
this.name = name;
this.polygon = polygon;
this.markers = [];
this.markersVisible = false;
}
//addMarker utilizes googles geometry library!
Neighborhood.prototype.addMarker = function (marker) {
var isInPoly = google.maps.geometry.poly.containsLocation(marker.getPosition(), this.polygon);
if (isInPoly) {
this.markers.push(marker);
}
return isInPoly;
};
Neighborhood.prototype.setMarkersVisible = function (bool) {
for (var i = 0, len = this.markers.length; i < len; i++) {
this.markers[i].setVisible(bool);
}
this.markersVisible = bool;
};
Neighborhood.prototype.zoomTo = function () {
var bounds = new google.maps.LatLngBounds(),
path = this.polygon.getPath(),
map = this.polygon.getMap();
path.forEach(function (obj, idx) {
bounds.extend(obj);
});
map.fitBounds(bounds);
};
下面的例子利用谷歌的地方库来加载多达 60 个(实际上我认为它得到大约 54 个)不同位置的星巴克在曼哈顿(我相信还有更多,但这是谷歌的结果限制)。它的工作原理是,在 initialize() 函数中,我们设置地图,然后使用 ajax 加载包含我们需要的社区名称和坐标的“36061_minimal.json”文件,然后 [private] setupNeighborhoods() 函数利用该数据创建多边形并将它们添加到我们的 NeighborhoodGroup 实例中,然后 [private] loadPlaces() 函数用于将标记对象添加到地图中,并将标记注册到我们的 NeighborhoodGroup 实例中。上例子:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Manhattan Neighborhoods</title>
<!--
NeighborhoodGroup.js requires that the geometry library be loaded,
just this example utilizes the places library
-->
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=geometry,places"></script>
<script type="text/javascript" src="NeighborhoodGroup.js"></script>
<script>
/***
The '36061_minimal.json' file is derived from '36061.json' file
obtained from the-neighborhoods-project at:
http://zetashapes.com/editor/36061
***/
//for this example, we will just be using random colors for our polygons, from the array below
var aBunchOfColors = [
'Aqua', 'Aquamarine', 'Blue', 'BlueViolet', 'Brown', 'BurlyWood', 'CadetBlue', 'Chartreuse', 'Chocolate', 'Coral', 'CornflowerBlue', 'Crimson', 'Cyan', 'DarkBlue', 'DarkCyan', 'DarkGoldenRod', 'DarkGray', 'DarkGreen', 'DarkKhaki', 'DarkMagenta', 'DarkOliveGreen', 'Darkorange', 'DarkOrchid', 'DarkRed', 'DarkSalmon', 'DarkSeaGreen', 'DarkSlateBlue', 'DarkSlateGray', 'DarkTurquoise', 'DarkViolet', 'DeepPink', 'DeepSkyBlue', 'DodgerBlue', 'FireBrick', 'ForestGreen', 'Fuchsia', 'Gold', 'GoldenRod', 'Gray', 'Green', 'GreenYellow', 'HotPink', 'IndianRed', 'Indigo', 'LawnGreen', 'Lime', 'LimeGreen', 'Magenta', 'Maroon', 'MediumAquaMarine', 'MediumBlue', 'MediumOrchid', 'MediumPurple', 'MediumSeaGreen', 'MediumSlateBlue', 'MediumSpringGreen', 'MediumTurquoise', 'MediumVioletRed', 'MidnightBlue', 'Navy', 'Olive', 'OliveDrab', 'Orange', 'OrangeRed', 'Orchid', 'PaleGreen', 'PaleTurquoise', 'PaleVioletRed', 'Peru', 'Pink', 'Plum', 'Purple', 'Red', 'RosyBrown', 'RoyalBlue', 'SaddleBrown', 'Salmon', 'SandyBrown', 'SeaGreen', 'Sienna', 'SkyBlue', 'SlateBlue', 'SlateGray', 'SpringGreen', 'SteelBlue', 'Tan', 'Teal', 'Thistle', 'Tomato', 'Turquoise', 'Violet', 'Wheat', 'Yellow', 'YellowGreen'
];
Array.prototype.randomItem = function () {
return this[Math.floor(Math.random()*this.length)];
};
function initialize() {
var i,
hoodGroup = new NeighborhoodGroup('Manhattan'),
polys = [],
gm = google.maps,
xhr = getXhr(), //will use this to load json via ajax
mapOptions = {
zoom: 11,
scaleControl: true,
center: new gm.LatLng(40.79672159345707, -73.952665677124),
mapTypeId: gm.MapTypeId.ROADMAP,
},
map = new gm.Map(document.getElementById('map_canvas'), mapOptions),
service = new google.maps.places.PlacesService(map),
infoWindow = new gm.InfoWindow();
function setMarkerClickHandler(marker, infoWindowContent) {
google.maps.event.addListener(marker, 'click', function () {
if (!(infoWindow.anchor == this) || !infoWindow.isVisible) {
infoWindow.setContent(infoWindowContent);
infoWindow.open(map, this);
} else {
infoWindow.close();
}
infoWindow.isVisible = !infoWindow.isVisible;
infoWindow.anchor = this;
});
}
/*******
* the loadPlaces function below utilizes googles places library to load
* locations of up to 60 starbucks stores in Manhattan. You should replace
* the code in this function with your own to just add Marker objects to
*the map, though it's important to still use the line below which reads:
* hoodGroup.addMarker(marker);
* and I'd also strongly recommend using the setMarkerClickHandler function as below
*******/
function loadPlaces() {
var placesResults = [],
request = {
location: mapOptions.center,
radius: 25 / 0.00062137, //25 miles converted to meters
query: 'Starbucks in Manhattan'
};
function isDuplicateResult(res) {
for (var i = 0; i < placesResults.length; i++) {
if (res.formatted_address == placesResults[i].formatted_address) {
return true;
}
}
placesResults.push(res);
return false;
}
service.textSearch(request, function (results, status, pagination) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var res, marker, i = 0, len = results.length; i < len; i++) {
res = results[i];
if (!isDuplicateResult(res)) {
marker = new google.maps.Marker({
map: map,
visible: false,
position: res.geometry.location
});
setMarkerClickHandler(marker, res.name + '<br>' + res.formatted_address);
hoodGroup.addMarker(marker);
}
}
}
if (pagination && pagination.hasNextPage) {
pagination.nextPage();
}
});
}
function setupNeighborhoods(arr) {
var item, poly, j,
i = 0,
len = arr.length,
polyOptions = {
strokeWeight: 0, //best with no stroke outline I feel
fillOpacity: 0.4,
map: map
};
for (; i < len; i++) {
item = arr[i];
for (j = 0; j < item[1][0].length; j++) {
var tmp = item[1][0][j];
item[1][0][j] = new gm.LatLng(tmp[1], tmp[0]);
}
color = aBunchOfColors.randomItem();
polyOptions.fillColor = color;
polyOptions.paths = item[1][0];
poly = new gm.Polygon(polyOptions);
hoodGroup.addNeighborhood(item[0], poly);
}
loadPlaces();
}
//begin ajax code to load our '36061_minimal.json' file
if (xhr !== null) {
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
setupNeighborhoods(eval('(' + xhr.responseText + ')'));
} else {
alert('failed to load json via ajax!');
}
}
};
xhr.open('GET', '36061_minimal.json', true);
xhr.send(null);
}
}
google.maps.event.addDomListener(window, 'load', initialize);
function getXhr() {
var xhr = null;
try{//Mozilla, Safari, IE 7+...
xhr = new XMLHttpRequest();
if (xhr.overrideMimeType) {
xhr.overrideMimeType('text/xml');
}
} catch(e) {// IE 6, use only Msxml2.XMLHTTP.(6 or 3).0,
//see: http://blogs.msdn.com/xmlteam/archive/2006/10/23/using-the-right-version-of-msxml-in-internet-explorer.aspx
try{
xhr = new ActiveXObject("Msxml2.XMLHTTP.6.0");
}catch(e){
try{
xhr = new ActiveXObject("Msxml2.XMLHTTP.3.0");
}catch(e){}
}
}
return xhr;
}
</script>
</head>
<body>
<div id="map_canvas" style="width:780px; height:600px; margin:10px auto;"></div>
</body>
</html>
对于社区边界,您需要查看第三方供应商,例如Maponics(现在是 Pitney-Bowes 的一部分)。以下是 Realtor.com 在不同平台上使用 Maponics 社区边界的示例:https ://www.realtor.com/realestateandhomes-search/Greenwich-Village_New-York_NY#/lat-40.731/lng--73.994/zl-15