在Google地图上绘制清洁的邻域边界

时间:2013-07-10 15:18:40

标签: javascript jquery google-maps

我有一张谷歌地图,在整个曼哈顿城都有很多针脚。为了更好地组织这个幽闭恐怖的针脚,我想提供一个缩小的视图,将曼哈顿划分为可以点击的干净描绘的街区,然后放大并显示该邻域区域中的各个针脚。这是我想要实现的一个例子:

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)我可以获得有关如何绘制曼哈顿邻域边界的有意义信息。

任何人都有这方面的经验吗?

2 个答案:

答案 0 :(得分:5)

幸运的是,我找到了一个网站,你可以在GeoJson格式中获得关于邻域边界的精彩信息。有没有听说过“邻里项目”?它在http://zetashapes.com/editor/36061我在那里搜索了“曼哈顿”并找到了该页面。他们也有许多其他城市街区。正如您将注意到的那样,有一个按钮可以将GeoJson数据下载为.json文件。 现在,我觉得作为网站管理员和我们的责任是我们的责任。开发人员确保用户不需要下载超过必要的数据,以及减少我们的带宽需求,并且我发现GeoJson臃肿且过于庞大,无法满足我们的需求。因此,首先要在您的服务器或localhost上创建一个.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'文件。 O.k,现在已经处理了,对于下面的示例,您将需要以下javascript文件,其中有一个NeighborhoodGroup构造函数,用于跟踪我们的不同邻域。关于它的最重要的事情是你应该实例化一个邻居组的新实例,然后你通过调用它的addNeighborhood(名称,多边形)方法添加邻居,你提供一个名称和一个google.maps.Polygon实例,然后您可以通过调用addMarker(marker)方法&amp;添加标记对象到您的邻居组。给它一个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 place库加载最多60个(实际上我认为它大约有54个)星巴克在曼哈顿的不同位置(我相信还有更多,但这是googles结果限制)。它是如何工作的,在initialize()函数中我们设置了map,然后使用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>

答案 1 :(得分:1)

对于邻里边界,您需要查看第三方供应商,例如Maponics (now part of Pitney-Bowes)。以下是Realtor.com在不同平台上使用Maponics邻域边界的示例:https://www.realtor.com/realestateandhomes-search/Greenwich-Village_New-York_NY#/lat-40.731/lng--73.994/zl-15