我有一张谷歌地图,上面有很多大头针在曼哈顿全城都有。为了更好地组织这种幽闭恐惧症的大头针,我想提供一个缩小的视图,将曼哈顿划分为几个清晰的社区,你可以点击这些社区,然后放大并显示该社区区域中的各个大头针。下面是我想要实现的一个示例:
http://42floors.com/ny/new-york?where%5Bbounds%5D%5B%5D=40.81910776309414&where%5Bbounds%5D%5B%5D=-73.87714974792482&where%5Bbounds%5D%5B%5D=40.74046602072578&where%5Bbounds%5D%5B%5D=-74.07713525207521&where%5Bzoom%5D=13
我不知道从哪里开始。我已经阅读了google地图文档,但我仍然不确定(a)我应该使用什么javascript方法来绘制边界,以及(b)我在哪里可以获得关于如何绘制曼哈顿邻里边界的有意义的信息。
有人有这方面的经验吗?
发布于 2013-07-15 18:44:49
幸运的是,我找到了一个网站,在那里你可以以GeoJson格式获得关于邻里边界的大量信息。听说过“邻里计划”吗?就是在这里,我搜索了“http://zetashapes.com/editor/36061”,找到了那个页面。他们还有很多其他的城市社区。正如您将注意到的,有一个按钮可以将GeoJson数据下载为.json文件。现在,我觉得作为网站管理员和开发人员,我们有责任确保用户不需要下载更多的数据,同时降低我们的带宽要求,我发现GeoJson过于臃肿,对于我们需要从它获得的东西来说太大了。所以,第一件事是在你的服务器或本地主机上创建一个.php文件,并将其命名为'reduce.php‘或任何你想要的名称,然后用以下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(名称,多边形)方法向它添加邻居,然后你可以通过调用addMarker (标记)方法将标记对象添加到你的邻居组中,并为它提供一个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);
};下面的例子利用googles位置库加载了曼哈顿星巴克的60个不同位置(实际上我认为大约有54个)(我相信还有更多,但这是googles结果限制)。它的工作原理是,在initialize()函数中,我们设置地图,然后使用ajax加载'36061_minimal.json‘文件,该文件包含我们需要的邻域名称和坐标,然后私有setupNeighborhoods()函数利用这些数据创建多边形并将其添加到我们的NeighborhoodGroup实例中,然后使用私有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>发布于 2013-07-15 01:42:26
对于邻里边界,你需要寻找像Maponics (now part of Pitney-Bowes)这样的第三方供应商。以下是在不同平台上使用Maponics邻域边界的Realtor.com示例:https://www.realtor.com/realestateandhomes-search/Greenwich-Village_New-York_NY#/lat-40.731/lng--73.994/zl-15
https://stackoverflow.com/questions/17574507
复制相似问题