gpt4 book ai didi

javascript - 在谷歌地图上绘制干净的邻里边界

转载 作者:行者123 更新时间:2023-11-30 08:06:25 24 4
gpt4 key购买 nike

我有一张谷歌地图,在整个曼哈顿市放置了很多图钉。为了更好地组织这些密密麻麻的图钉,我想提供一个缩小 View ,将曼哈顿划分为清晰划定的社区,您可以单击这些区域,然后放大并显示该邻里区域中的各个图钉。这是我想要实现的示例:

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

我不确定从哪里开始。我已经阅读了谷歌地图文档,但我仍然不确定 (a) 我应该使用什么 javascript 方法来绘制边界,以及 (b) 我在哪里可以获得关于如何绘制曼哈顿邻里边界的有意义的信息。

谁有这方面的经验?

最佳答案

幸运的是,我找到了一个网站,您可以在其中获得有关 GeoJson 格式的邻域边界的重要信息。听说过“the-neighborhoods-project”吗?在这里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(name, polygon) 方法向它添加邻居,你输入一个名称和一个 google.maps.Polygon 实例,然后您可以通过调用 addMarker(marker) 方法并将标记对象添加到您的社区组并为其提供一个 google.maps.Marker 对象,如果可能,标记将被委托(delegate)给适当的社区,否则 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 places 库加载曼哈顿最多 60 个(实际上我认为大约有 54 个)星巴克的不同位置(我相信不止这些,但这是 googles 结果的限制)。它是如何工作的,在我们设置 map 的 initialize() 函数中,然后使用 ajax 加载我们的“36061_minimal.json”文件,其中包含我们需要的社区名称和坐标,然后 [private] setupNeighborhoods() 函数利用该数据创建多边形并将它们添加到我们的 NeighborhoodGroup 实例,然后使用 [private] loadPlaces() 函数将标记对象添加到 map ,并将标记注册到我们的 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>

关于javascript - 在谷歌地图上绘制干净的邻里边界,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17574507/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com