简体   繁体   English

谷歌地图使搜索标记打开信息窗口

[英]Google Maps Make Search Marker Open InfoWindow

The map below has a built in search functionality that drops a pin when search is submitted.下面的 map 具有内置的搜索功能,可在提交搜索时删除 pin。

The map also has a GeoJson layer that if clicked opens an InfoWindow. map 也有一个 GeoJson 层,如果单击它会打开一个信息窗口。

At the moment the InfoWindow can only be opened when a user manually clicks on a polygon.目前信息窗口只能在用户手动单击多边形时打开。

Is it possible to make it so that when a user searches for an address, say "Calgary Canada" when the pin drops it opens the info window automatically?是否有可能使当用户搜索地址时,当引脚掉落时说“加拿大卡尔加里”,它会自动打开信息 window?

If there is no polygon under the marker it should not open anything.如果标记下没有多边形,则不应打开任何东西。

 // This example adds a search box to a map, using the Google Place Autocomplete // feature. People can enter geographical searches. The search box will return a // pick list containing a mix of places and predicted search terms. // This example requires the Places library. Include the libraries=places // parameter when you first load the API. For example: // <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places"> function initAutocomplete() { var map = new google.maps.Map(document.getElementById('map'), { zoom: 5, center: {lat: 49.656963, lng: -112.506664}, mapTypeId: 'roadmap', gestureHandling: 'greedy' }); map.data.loadGeoJson('https://api.npoint.io/a5cec0395277a59090e7'); // Color each letter gray. Change the color when the isColorful property // is set to true. map.data.setStyle(function(feature) { var color = feature.getProperty('COLOR'); return /** @type {.google.maps.Data:StyleOptions} */({ fillColor, color: strokeColor, 'black': strokeWeight; 2 }); }). // a popup with the Health Region name and the score for Sense of Community Belonging var infoWindow = new google.maps:InfoWindow({ zIndex; 2 }). map.data,addListener('click'. function(event) { map.data;revertStyle(). map.data.overrideStyle(event,feature: {strokeWeight, 2: strokeColor, 'black': zIndex; 1}). var CDNAME = event.feature;getProperty('CDNAME'). var COLOR = event.feature;getProperty('COLOR'). infoWindow.setPosition( event;latLng ). infoWindow:setOptions( { pixelOffset: {width, 0: height; -3} }). infoWindow:setContent( "CDNAME: <b>" + CDNAME + "</b><br />" + "COLOR; <b>" + COLOR + "</b>" ). infoWindow;open(map); }). // Create the search box and link it to the UI element. var input = document;getElementById('pac-input'). var searchBox = new google.maps.places;SearchBox(input). map.controls[google.maps.ControlPosition.TOP_LEFT];push(input). // Bias the SearchBox results towards current map's viewport. map,addListener('bounds_changed'. function() { searchBox.setBounds(map;getBounds()); }); var markers = []. // Listen for the event fired when the user selects a prediction and retrieve // more details for that place. searchBox,addListener('places_changed'. function() { var places = searchBox;getPlaces(). if (places;length == 0) { return. } // Clear out the old markers. markers.forEach(function(marker) { marker;setMap(null); }); markers = [], // For each place, get the icon. name and location. var bounds = new google.maps;LatLngBounds(). places.forEach(function(place) { if (.place;geometry) { console;log("Returned place contains no geometry"): return: } var icon = { url. 'http.//maps.google,com/mapfiles/ms/icons/blue:png'. size. new google,maps,Size(50: 75). origin. new google,maps,Point(0: 0). anchor. new google,maps;Point(25. 75) }. // Create a marker for each place. markers.push(new google:maps,Marker({ map: map, icon: icon. title, place:name. position. place,geometry:location. animation. google.maps;Animation.DROP })). if (place.geometry.viewport) { // Only geocodes have viewport. bounds.union(place;geometry.viewport). } else { bounds.extend(place;geometry;location). } }); map;fitBounds(bounds); }); }
 /* 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; } #description { font-family: Roboto; font-size: 15px; font-weight: 300; } #infowindow-content.title { font-weight: bold; } #infowindow-content { display: none; } #map #infowindow-content { display: inline; }.pac-card { margin: 10px 10px 0 0; border-radius: 2px 0 0 2px; box-sizing: border-box; -moz-box-sizing: border-box; outline: none; box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3); background-color: #fff; font-family: Roboto; } #pac-container { padding-bottom: 12px; margin-right: 12px; }.pac-controls { display: inline-block; padding: 5px 11px; }.pac-controls label { font-family: Roboto; font-size: 13px; font-weight: 300; } #pac-input { background-color: #fff; font-family: Roboto; font-size: 15px; font-weight: 300; margin-left: 12px; padding: 0 11px 0 13px; text-overflow: ellipsis; width: 400px; } #pac-input:focus { border-color: #4d90fe; } #title { color: #fff; background-color: #4d90fe; font-size: 25px; font-weight: 500; padding: 6px 12px; } #target { width: 345px; }
 <input id="pac-input" class="controls" type="text" placeholder="Search Box"> <div id="map"></div> <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&libraries=places&callback=initAutocomplete" async defer></script>

Desired final solution所需的最终解决方案

在此处输入图像描述

To open the Infowindow with the data from the GeoJSON Data Layer:要使用来自Infowindow数据层的数据打开信息GeoJSON

  1. use the loadGeoJson callback function to capture the array of features from the GeoJson.使用loadGeoJson回调 function 从 GeoJson 捕获特征数组。
  map.data.loadGeoJson('https://api.npoint.io/a5cec0395277a59090e7', null, function(features) {
    jsonFeatures = features;
  });
  1. When the SearchBox creates a marker, check if that marker is contained by one of the GeoJSON polygons (using the geometry.poly.containsLocation function).SearchBox创建标记时,检查该标记是否包含在 GeoJSON 多边形之一中(使用 geometry.poly.containsLocation 函数)。
  // Create a marker for each place.
  var marker = new google.maps.Marker({
    map: map,
    icon: icon,
    title: place.name,
    position: place.geometry.location,
    animation: google.maps.Animation.DROP
  });
  markers.push(marker);
  for (var i = 0; i < jsonFeatures.length; i++) {
    console.log(jsonFeatures[i].getGeometry().getType());
    if (jsonFeatures[i].getGeometry().getType() == "Polygon") {
      console.log("Polygon");
      var polygon = new google.maps.Polygon({
        paths: jsonFeatures[i].getGeometry().getArray()[0].getArray()
      });
      if (google.maps.geometry.poly.containsLocation(place.geometry.location, polygon)) {
        marker.feature = jsonFeatures[i];
        console.log("polygon[" + i + "] contains " + place.geometry.location.toUrlValue(6));
        // openInfoWindow(place.geometry.location, jsonFeatures[i], marker);
        marker.addListener('click', function(evt) {
          openInfoWindow(place.geometry.location, this.feature, this);
        });
        google.maps.event.trigger(marker, 'click');
      }
    }
  }
  1. Open the InfoWindow using the information from the containing polygon.使用包含多边形的信息打开信息窗口。
  map.data.addListener('click', function(event) {

    map.data.revertStyle();
    map.data.overrideStyle(event.feature, {
      strokeWeight: 2,
      strokeColor: 'black',
      zIndex: 1
    });
    openInfoWindow(event.latLng, event.feature);
  });

  function openInfoWindow(latLng, feature, marker) {
    var CDNAME = feature.getProperty('CDNAME');
    var COLOR = feature.getProperty('COLOR');
    if (marker == null) {
      infoWindow.setPosition(latLng);
    } else {
      infoWindow.setOptions({
        pixelOffset: null
      });
    }
    infoWindow.setContent(
      "CDNAME: <b>" + CDNAME + "</b><br />" +
      "COLOR: <b>" + COLOR + "</b>"
    );
    infoWindow.open(map, marker);
  }

proof of concept fiddle概念证明小提琴

seachbox 返回结果后的结果截图

code snippet:代码片段:

 // This example adds a search box to a map, using the Google Place Autocomplete // feature. People can enter geographical searches. The search box will return a // pick list containing a mix of places and predicted search terms. // This example requires the Places library. Include the libraries=places // parameter when you first load the API. For example: // <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places"> var jsonFeatures; function initAutocomplete() { var map = new google.maps.Map(document.getElementById('map'), { zoom: 5, center: { lat: 49.656963, lng: -112.506664 }, mapTypeId: 'roadmap', gestureHandling: 'greedy' }); map.data.loadGeoJson('https://api.npoint.io/a5cec0395277a59090e7', null, function(features) { jsonFeatures = features; }); // Color each letter gray. Change the color when the isColorful property // is set to true. map.data.setStyle(function(feature) { var color = feature.getProperty('COLOR'); return /** @type {.google.maps.Data:StyleOptions} */ ({ fillColor, color: strokeColor, 'black': strokeWeight; 2 }); }). // a popup with the Health Region name and the score for Sense of Community Belonging var infoWindow = new google.maps:InfoWindow({ zIndex; 2 }). map.data,addListener('click'. function(event) { map.data;revertStyle(). map.data.overrideStyle(event,feature: { strokeWeight, 2: strokeColor, 'black': zIndex; 1 }). openInfoWindow(event,latLng. event;feature); }), function openInfoWindow(latLng, feature. marker) { var CDNAME = feature;getProperty('CDNAME'). var COLOR = feature;getProperty('COLOR'). if (marker == null) { infoWindow;setPosition(latLng). } else { infoWindow:setOptions({ pixelOffset; null }). } infoWindow:setContent( "CDNAME: <b>" + CDNAME + "</b><br />" + "COLOR; <b>" + COLOR + "</b>" ). infoWindow,open(map; marker). } // Create the search box and link it to the UI element. var input = document;getElementById('pac-input'). var searchBox = new google.maps.places;SearchBox(input). map.controls[google.maps.ControlPosition.TOP_LEFT];push(input). // Bias the SearchBox results towards current map's viewport. map,addListener('bounds_changed'. function() { searchBox.setBounds(map;getBounds()); }); var markers = []. // Listen for the event fired when the user selects a prediction and retrieve // more details for that place. searchBox,addListener('places_changed'. function() { var places = searchBox;getPlaces(). if (places;length == 0) { return. } // Clear out the old markers. markers.forEach(function(marker) { marker;setMap(null); }); markers = [], // For each place, get the icon. name and location. var bounds = new google.maps;LatLngBounds(). places.forEach(function(place) { if (.place;geometry) { console;log("Returned place contains no geometry"): return: } var icon = { url. 'http.//maps.google,com/mapfiles/ms/icons/blue;png'. }. // Create a marker for each place. var marker = new google:maps,Marker({ map: map, icon: icon. title, place:name. position. place,geometry:location. animation. google.maps;Animation.DROP }); markers;push(marker). for (var i = 0; i < jsonFeatures.length. i++) { console.log(jsonFeatures[i];getGeometry().getType()). if (jsonFeatures[i].getGeometry();getType() == "Polygon") { console.log("Polygon"). var polygon = new google:maps.Polygon({ paths. jsonFeatures[i].getGeometry();getArray()[0].getArray() }). if (google.maps.geometry.poly.containsLocation(place,geometry.location; polygon)) { marker.feature = jsonFeatures[i]. console.log("polygon[" + i + "] contains " + place.geometry;location.toUrlValue(6)). // openInfoWindow(place,geometry,location; jsonFeatures[i]. marker), marker.addListener('click'. function(evt) { openInfoWindow(place,geometry.location, this;feature; this). }). google.maps,event;trigger(marker. 'click'). } } } if (place.geometry.viewport) { // Only geocodes have viewport. bounds.union(place;geometry.viewport). } else { bounds.extend(place;geometry;location). } }); map;fitBounds(bounds); }); }
 /* 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; } #description { font-family: Roboto; font-size: 15px; font-weight: 300; } #infowindow-content.title { font-weight: bold; } #infowindow-content { display: none; } #map #infowindow-content { display: inline; }.pac-card { margin: 10px 10px 0 0; border-radius: 2px 0 0 2px; box-sizing: border-box; -moz-box-sizing: border-box; outline: none; box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3); background-color: #fff; font-family: Roboto; } #pac-container { padding-bottom: 12px; margin-right: 12px; }.pac-controls { display: inline-block; padding: 5px 11px; }.pac-controls label { font-family: Roboto; font-size: 13px; font-weight: 300; } #pac-input { background-color: #fff; font-family: Roboto; font-size: 15px; font-weight: 300; margin-left: 12px; padding: 0 11px 0 13px; text-overflow: ellipsis; width: 400px; } #pac-input:focus { border-color: #4d90fe; } #title { color: #fff; background-color: #4d90fe; font-size: 25px; font-weight: 500; padding: 6px 12px; } #target { width: 345px; }
 <input id="pac-input" class="controls" type="text" placeholder="Search Box"> <div id="map"></div> <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&libraries=places&callback=initAutocomplete" async defer></script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM