Google地图JavaScriptApi如何针对不同位置的查询结果添加不同的标签?

How to add different labels in respect of different locations query result with Google Maps JavaScript Api?

我在地图 JS 中有一个代码 api。我有 2 个查询搜索,一个用于寻找附近的药房,另一个用于医院。我想将 returning 标记标记为 F 表示药房,H 表示医院。我如何进行这种分离?我如何查询以搜索医院和药房?我尝试了很多组合,但它 return 仅限于医院或药房。

<script
        src="https://maps.googleapis.com/maps/api/js?key=AIzaSyD6uiXpiTDkhGcAG9X4G8vm1rF2eXQzXMI&callback=initialize&libraries=places&v=weekly"
        defer></script>

let map;
        let service;
        let infowindow;
        function initialize() {
            infowindow = new google.maps.InfoWindow();
            //Map options
            var options = {
                center: userPosition,
                zoom: 14,
                // disableDefaultUI: true,
            }
            //New map
            map = new
                google.maps.Map(document.getElementById("map"), options);

            var request = {
                location: userPosition,
                radius: '2000',
                query: "hospital, pharmacy",
                // query: 'spital',
            };

            service = new google.maps.places.PlacesService(map);
            service.textSearch(request, callback);;

            function addUserLocationMarker() {
                marker = new google.maps.Marker({
                    map,
                    draggable: true,
                    animation: google.maps.Animation.DROP,
                    position: userPosition,
                    icon: "http://maps.google.com/mapfiles/kml/pushpin/grn-pushpin.png"
                });

                marker.addListener("click", toggleBounce);
                var infoWindow = new google.maps.InfoWindow({
                    content: "<h3>Locatia mea ! </h3>"
                });
                marker.addListener('click', function () {
                    infoWindow.open(map, marker);
                });
            }
            addUserLocationMarker();
        }

        let neighborhoods = [];

        function callback(results, status) {
                if (status == google.maps.places.PlacesServiceStatus.OK) {
                    for (var i = 0; i < results.length; i++) {
                        var place = results[i];
                        // createMarker(results[i]);
                        drop(results);
                    }
                }
            }

        let markers = [];

        function drop(neighborhoods) {
                clearMarkers();
                for (let i = 0; i < neighborhoods.length; i++) {
                    addMarkerWithTimeout(neighborhoods[i], i * 200);
                }
            }

        function addMarkerWithTimeout(place, timeout) {
                window.setTimeout(() => {
                    var marker = new google.maps.Marker({
                        map,
                        position: place.geometry.location,
                        animation: google.maps.Animation.DROP,

                    });
                    google.maps.event.addListener(marker, "click", () => {
                        infowindow.setContent('<h2>' + place.name + '</h2>');
                        infowindow.open(map, marker);
                    }),
                        marker.addListener("click", toggleBounce);
                    markers.push(marker);
                }, timeout);
            }

        function clearMarkers() {
            for (let i = 0; i < markers.length; i++) {
                markers[i].setMap(null);
            }
            markers = [];
        }

        function toggleBounce() {
            if (marker.getAnimation() !== null) {
                marker.setAnimation(null);
            } else {
                marker.setAnimation(google.maps.Animation.BOUNCE);
            }
        }

        function ipLookup() {
            $.get('https://api.userinfo.io/userinfos', function (r) {
                showUserDetails(r.position.latitude, r.position.longitude, r);
            });
        }
    </script>

使用地点库(作为地图 Javascript API 的一部分)执行 text search 时,如果您提供 type,如文档中所述。

但是type只支持一个类型。因此,您必须提出 2 个单独的请求,一个带有 pharmacy 类型,一个带有 hospital 类型,并相应地添加您的标记。没什么大不了的。

可以 可能会省略类型并使用类似 hospital, pharmacy 的内容作为文本查询,但结果可能质量不同(根据我的测试,它没有 return 很多地方 and/or 所有相关的地方)。因此,IMO 的最佳选择是进行单独的查询。当然,您会收到相应的账单。

示例:

创建您的 2 个请求对象

var request_hospital = {
  location: userPosition,
  radius: '2000',
  type: 'hospital'
};

var request_pharmacy = {
  location: userPosition,
  radius: '2000',
  type: 'pharmacy'
};

然后您可能需要在不同的回调中处理结果,以便您可以相应地处理医院和药房标记

service.textSearch(request_hospital, callback_hospital);
service.textSearch(request_pharma, callback_pharma);

或者,由于您不会搜索任何特定文本,而只会根据地点 类型 发出请求,您也可以使用 nearbySearch 而不是 textSearch.

service.nearbySearch(request_hospital, callback_hospital);
service.nearbySearch(request_pharma, callback_pharma);

您应该同时尝试这两种服务,看看哪一种服务 return 最适合您。参见 Nearby Search requests

获得药房和医院结果的最可靠方法是提出两种不同的请求,一种针对药房,一种针对医院。要以不同方式标记标记,请将适当的标签传递给回调函数。

药店申请:

var requestF = {
    location: userPosition,
    radius: '2000',
    query: 'pharmacy',
}; 
function callbackF(results, status) {
  if (status == google.maps.places.PlacesServiceStatus.OK) {
    for (var i = 0; i < results.length; i++) {
      var place = results[i];
      // createMarker(results[i]);
      drop(results, "F");
    }
  }
}
service.textSearch(requestF, callbackF);

要求医院:

var requestH = {
    location: userPosition,
    radius: '2000',
    query: 'hospital',
};
function callbackH(results, status) {
  if (status == google.maps.places.PlacesServiceStatus.OK) {
    for (var i = 0; i < results.length; i++) {
      var place = results[i];
      // createMarker(results[i]);
      drop(results, "H");
    }
  }
}
service.textSearch(requestH, callbackH);

更新了 drop 函数:

function drop(neighborhoods, label) {

  clearMarkers();

  for (let i = 0; i < neighborhoods.length; i++) {
    addMarkerWithTimeout(neighborhoods[i], label, i * 200);

  }
}

更新了 addMarkerWithTimeout 函数:

function addMarkerWithTimeout(place, label, timeout) {
  window.setTimeout(() => {
    var marker = new google.maps.Marker({
      map,
      position: place.geometry.location,
      animation: google.maps.Animation.DROP,
      label: label
    });
    google.maps.event.addListener(marker, "click", () => {
        infowindow.setContent('<h2>' + place.name + '</h2>');
        infowindow.open(map, marker);
      }),
      marker.addListener("click", toggleBounce);
    markers.push(marker);
  }, timeout);
}

proof of concept fiddle

代码片段:

let map;
let service;
let infowindow;
let userPosition = {
  lat: 40.7127753,
  lng: -74.0059728
}

function initialize() {
  infowindow = new google.maps.InfoWindow();
  //Map options
  var options = {
    center: userPosition,
    zoom: 15,
    // disableDefaultUI: true,
  }
  //New map
  map = new
  google.maps.Map(document.getElementById("map"), options);

  var requestF = {
    location: userPosition,
    radius: '2000',
    query: 'pharmacy',
  };

  service = new google.maps.places.PlacesService(map);
  service.textSearch(requestF, callbackF);

  var requestH = {
    location: userPosition,
    radius: '2000',
    query: 'hospital',
  };
  service.textSearch(requestH, callbackH);

  function addUserLocationMarker() {
    marker = new google.maps.Marker({
      map,
      draggable: true,
      animation: google.maps.Animation.DROP,
      position: userPosition,
      icon: "http://maps.google.com/mapfiles/kml/pushpin/grn-pushpin.png"
    });

    marker.addListener("click", toggleBounce);
    var infoWindow = new google.maps.InfoWindow({
      content: "<h3>Locatia mea ! </h3>"
    });
    marker.addListener('click', function() {
      infoWindow.open(map, marker);
    });
  }
  addUserLocationMarker();
}

function callbackF(results, status) {
  if (status == google.maps.places.PlacesServiceStatus.OK) {
    for (var i = 0; i < results.length; i++) {
      var place = results[i];
      // createMarker(results[i]);
      drop(results, "F");
    }
  }
}

function callbackH(results, status) {
  if (status == google.maps.places.PlacesServiceStatus.OK) {
    for (var i = 0; i < results.length; i++) {
      var place = results[i];
      // createMarker(results[i]);
      drop(results, "H");
    }
  }
}

let markers = [];

function drop(neighborhoods, label) {

  clearMarkers();

  for (let i = 0; i < neighborhoods.length; i++) {
    addMarkerWithTimeout(neighborhoods[i], label, i * 200);

  }
}

function addMarkerWithTimeout(place, label, timeout) {
  window.setTimeout(() => {
    var marker = new google.maps.Marker({
      map,
      position: place.geometry.location,
      animation: google.maps.Animation.DROP,
      label: label
    });
    google.maps.event.addListener(marker, "click", () => {
        infowindow.setContent('<h2>' + place.name + '</h2>');
        infowindow.open(map, marker);
      }),
      marker.addListener("click", toggleBounce);
    markers.push(marker);
  }, timeout);
}

function clearMarkers() {
  for (let i = 0; i < markers.length; i++) {
    markers[i].setMap(null);
  }
  markers = [];
}

function createMarker(place) {
  var marker = new google.maps.Marker({
    map,
    position: place.geometry.location,
    animation: google.maps.Animation.DROP,
    // place: AnimationEffect,
  });
  google.maps.event.addListener(marker, "click", () => {
    infowindow.setContent(place.name);
    infowindow.open(map, marker);
  });
  marker.addListener("click", toggleBounce);
}

function toggleBounce() {
  if (marker.getAnimation() !== null) {
    marker.setAnimation(null);
  } else {
    marker.setAnimation(google.maps.Animation.BOUNCE);
  }
}
/* Always set the map height explicitly to define the size of the div
       * element that contains the map. */

#map {
  height: 100%;
}


/* Optional: Makes the sample page fill the window. */

html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}
<!DOCTYPE html>
<html>

<head>
  <title>Place Searches</title>
  <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
  <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initialize&libraries=places&v=weekly" defer></script>
  <!-- jsFiddle will insert css and js -->
</head>

<body>
  <div id="map"></div>
</body>

</html>