javascript 如何在 Google Maps API 搜索结果中显示自定义地点?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23824133/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 01:38:06  来源:igfitidea点击:

How to display custom places in Google Maps API search results?

javascriptgoogle-mapsgoogle-maps-api-3google-maps-markerssearch-box

提问by timetowonder

So there is this basic example of a google map with a searchbox: https://developers.google.com/maps/documentation/javascript/examples/places-searchbox

所以有一个带有搜索框的谷歌地图的基本示例:https: //developers.google.com/maps/documentation/javascript/examples/places-searchbox

I want to accomplish something very simple. I'd like to just hardcode some locations (may be some simple array/object with their latitudes and longitudes) and then when you search for place, for example, "Washington", then those locations are displayed (with marker) if some of them are indeed inside Washington. If I search for "Africa" and some of my locations are inside africa, I want them to be displayed. And if I search for a place which has none of my locations, then they should simply be not displayed.

我想完成一些非常简单的事情。我只想硬编码一些位置(可能是一些带有纬度和经度的简单数组/对象),然后当您搜索位置时,例如“华盛顿”,然后显示这些位置(带有标记)如果他们确实在华盛顿内部。如果我搜索“非洲”并且我的一些位置在非洲境内,我希望它们显示出来。如果我搜索一个没有我的位置的地方,那么它们应该不会被显示。

I also found this — https://developers.google.com/places/documentation/actions#adding_a_place. But I am not sure if that is what I should use for my purpose (or should I?). And if it is, I'm not sure how to use it — where do I send the suggested JSON data?

我也发现了这个——https://developers.google.com/places/documentation/actions#adding_a_place。但我不确定这是否是我应该用于我的目的(或者我应该?)。如果是,我不确定如何使用它——我应该将建议的 JSON 数据发送到哪里?

Thanks in advance!

提前致谢!

回答by timetowonder

Alright, i've solved it! I'd like to share how it is done... I must say, programming world is new to me and hell it is very interesting :) And it is the first time I've used any kind of API... Here is a working example: http://codepen.io/everdimension/pen/LpfEH?editors=001

好的,我已经解决了!我想分享它是如何完成的......我必须说,编程世界对我来说是新的,而且非常有趣:) 这是我第一次使用任何类型的 API......这里是一个工作示例:http: //codepen.io/everdimension/pen/LpfEH?editors=001

Explained:

解释:

So, first thing you gotta know is how to add markers. That can be easily found in maps API documentation. The marker is added like that:

因此,您首先要知道的是如何添加标记。这可以在地图 API 文档中轻松找到。标记是这样添加的:

var marker = new google.maps.Marker({ marker_properties});

var marker = new google.maps.Marker({ marker_properties});

Ok, so how do we add all the markers for the places you have? Well, you simply iterate through the places which have coordinates. First, let's create the places array:

好的,那么我们如何为您拥有的地点添加所有标记?好吧,您只需遍历具有坐标的位置即可。首先,让我们创建 Places 数组:

var random_places = [
  ['Moscow1', 55.822083, 37.665453, 4],
  ['Moscow2', 55.604697, 37.642107, 4],
  ['Lisbon1', 38.749402, -9.120034, 4],
  ['Lisbon2', 38.708960, -9.169130, 4],
  ['NewYork1', 40.784513, -73.976630, 4],
  ['NewYork2', 40.707522, -74.037055, 4],
  ['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]
];

Ok, now let's iterate through these places and add a marker each time:

好的,现在让我们遍历这些地方并每次添加一个标记:

for (var i = 0; i < random_places.length; i++) {
    var beach = random_places[i];
    var myLatLng = new google.maps.LatLng(beach[1], beach[2]);
    var marker = new google.maps.Marker({
        position: myLatLng,
        map: map,
        title: beach[0],
    });
};

Ok, so this code just uses basic API functionality and should be no problem. But all the markers we've created exist on the map all the time, no matter if they are within the visible bounds or not. But we want the markers to appear only if they are within the part of the map we are looking at. Now that's exactly what my question was about. And here's how we can do it.

好的,所以这段代码只使用了基本的 API 功能,应该没有问题。但是我们创建的所有标记一直存在于地图上,无论它们是否在可见范围内。但是我们希望标记只有在我们正在查看的地图部分内时才会出现。现在这正是我的问题。这是我们如何做到的。

The key word is bounds. Turns out, with maps API we can make the following event listener:

关键词是bounds。事实证明,使用地图 API,我们可以制作以下事件侦听器:

google.maps.event.addListener(map, 'bounds_changed', function() { ... });

google.maps.event.addListener(map, 'bounds_changed', function() { ... });

And the function will execute each time the bounds of the maps are changed! What we have to do is check if the markers fall within the current bounds and if they do, we'll create them. So here:

每次更改地图的边界时都会执行该函数!我们要做的是检查标记是否在当前范围内,如果是,我们将创建它们。所以在这里:

var place_markers = [];

google.maps.event.addListener(map, 'bounds_changed', function() {

    var bounds = map.getBounds();
    searchBox.setBounds(bounds); // not needed for our purpose, it adds bias to new     searches

    var NE = bounds.getNorthEast();
    var SW = bounds.getSouthWest();

    // Iterate through all places
    for (var i = 0; i < random_places.length; i++) {
            var place_arr = random_places[i];

            // Check if a place is within bounds - not best way, explained later
            if ( (NE.lat() > place_arr[1] && place_arr[1] > SW.lat()) &&
                    (NE.lng() > place_arr[2] && place_arr[2] > SW.lng()) ) {

                    var myLatLng = new google.maps.LatLng(place_arr[1], place_arr[2]);
                    var marker = new google.maps.Marker({
                            position: myLatLng,
                            map: map,
                            title: place_arr[0],
        });

        place_markers.push(marker);

    }
};

});

That's it! Now the markers only get created when they are within the visible part of the map! You may have noticed that I had also created an empty place_markersobject and then had pushed all created marked into it. Why? Because we need to do one more thing. We'd want to remove all the created markers if they fall outside of current bounds! So each time the bounds are changed we would like for this code to execute:

而已!现在,只有在地图的可见部分内才会创建标记!您可能已经注意到,我还创建了一个空place_markers对象,然后将所有已创建的标记推入其中。为什么?因为我们还需要做一件事。如果它们超出当前范围,我们希望删除所有创建的标记!因此,每次更改边界时,我们都希望执行此代码:

// Remove out of bounds markers
for (var k = 0; k < place_markers.length; k++) {
  var one_marker = place_markers[k];
  if (!bounds.contains(one_marker.getPosition())) {
    one_marker.setMap(null);
  }
}

You can see that here I've used a built in bounds.contains()function to check if a created marker is within bounds. Same function can also be used when the markers are created, but I decided to leave the code like that to show the process of finding the correct solution. The main thing is that the markers are now being removed when they fall out of bounds and get created when they are within!

您可以看到这里我使用了一个内置bounds.contains()函数来检查创建的标记是否在边界内。创建标记时也可以使用相同的函数,但我决定保留这样的代码以显示找到正确解决方案的过程。最重要的是,标记现​​在在超出边界时被删除,并在它们进入时被创建!

One more thing I have to say. It's not the only way to accomplish the task I wanted. It can be done in many other ways. I have found a step-by-step explanation of an advanced way which uses PHP and MySQL: https://developers.google.com/maps/articles/phpsqlsearch_v3

我还要说一件事。这不是完成我想要的任务的唯一方法。它可以通过许多其他方式完成。我找到了使用 PHP 和 MySQL 的高级方法的分步说明:https: //developers.google.com/maps/articles/phpsqlsearch_v3

I hope this will be useful for someone who is, like me, new to google maps api.

我希望这对像我一样不熟悉 google maps api 的人有用。