Google Maps API v3 - Поместите круг Google Maps как Lat/Lng из окна поиска

Довольно новичок в этом, как показывает мой код. Код, который у меня есть, в основном был взят со страницы разработчиков Google для использования API Google Maps v3.

Я пытаюсь загрузить определенное количество местоположений из базы данных MySql в Карты Google с помощью PHP. Затем я хотел бы иметь возможность использовать результат lat/lng окна поиска, чтобы разместить редактируемый круг на карте, чтобы пользователь мог изменить радиус и переместить круг и увидеть, какие места покрыты кругом. Если пользователь выполняет новый поиск, я намерен удалить круг и снова заменить его на новую широту/долготу из окна поиска.

До сих пор мне удалось:

  1. Чтобы загрузить местоположения из MySql в Карты Google с помощью PHP
  2. Вставьте окно поиска, которое перемещается по найденному адресу
  3. Введите редактируемый круг на заданной широте/долготе. Здесь я не застрял, так как я хотел бы, чтобы редактируемый круг размещался динамически.

Любая помощь приветствуется. Спасибо.

21 января 2018 г., 19:35 по Гринвичу: новый пример кода ниже взят со страницы разработчика Google Maps, так как старая версия опубликованного кода имела ссылку Php на базу данных MySQL и не могла быть загружена кем-либо еще. Это пример кода окна поиска со страницы разработчиков Google (https://developers.google.com/maps/documentation/javascript/examples/places-searchbox), и я добавил очень простой код для добавления редактируемого круга.

Идея снова состоит в том, что когда пользователь ищет местоположение, вместо маркера, помещаемого на карту, помещается редактируемый круг. Каждый раз при поиске нового местоположения редактируемый круг удаляется с карты. У меня было бы поле ввода, в котором пользователь вводит радиус круга в метрах. Когда радиус вводится в поле, радиус круга изменяется, чтобы соответствовать ему.

Новый код:

 <!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <title>Places Searchbox</title>
    <style>
      /* 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;
      }
    </style>
  </head>
  <body>
    <input id="pac-input" class="controls" type="text" placeholder="Search Box">
    <div id="map"></div>
    <script>
      // 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'), {
          center: {lat: -33.8688, lng: 151.2195},
          zoom: 13,
          mapTypeId: 'roadmap'
        });

        // 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.

        //ADDING CIRCLE HERE - 21.01.20178 19:25PM GMT

        var circle = new google.maps.Circle ({
        map: map,
        center: new google.maps.LatLng (-33.856717, 151.215288),
        radius: 1000,
        strokeColor: "#00ff00",
        fillcolor: "red",
        editable: true
  });

        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: place.icon,
              size: new google.maps.Size(71, 71),
              origin: new google.maps.Point(0, 0),
              anchor: new google.maps.Point(17, 34),
              scaledSize: new google.maps.Size(25, 25)
            };

            // Create a marker for each place.
            markers.push(new google.maps.Marker({
              map: map,
              icon: icon,
              title: place.name,
              position: place.geometry.location
            }));

            if (place.geometry.viewport) {
              // Only geocodes have viewport.
              bounds.union(place.geometry.viewport);
            } else {
              bounds.extend(place.geometry.location);
            }
          });
          map.fitBounds(bounds);
        });
      }

    </script>
    <script src="https://maps.googleapis.com/maps/api/js?key=&libraries=places&callback=initAutocomplete"
         async defer></script>
  </body>
</html>

person CGarden    schedule 21.01.2018    source источник


Ответы (1)


Чтобы переместить круг к первому результату из SearchBox, установите центр круга в положение результатов. Добавьте это в обработку события place_changed:

if (index == 0) {
  circle.setCenter(place.geometry.location);
}

доказательство концепции скрипки

фрагмент кода:

function initAutocomplete() {
  var map = new google.maps.Map(document.getElementById('map'), {
    center: {
      lat: -33.8688,
      lng: 151.2195
    },
    zoom: 13,
    mapTypeId: 'roadmap'
  });

  // 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 = [];

  var circle = new google.maps.Circle({
    map: map,
    center: new google.maps.LatLng(-33.856717, 151.215288),
    radius: 1000,
    strokeColor: "#00ff00",
    fillcolor: "red",
    editable: true
  });

  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, index) {
      if (!place.geometry) {
        console.log("Returned place contains no geometry");
        return;
      }
      var icon = {
        url: place.icon,
        size: new google.maps.Size(71, 71),
        origin: new google.maps.Point(0, 0),
        anchor: new google.maps.Point(17, 34),
        scaledSize: new google.maps.Size(25, 25)
      };

      // Create a marker for each place.
      markers.push(new google.maps.Marker({
        map: map,
        icon: icon,
        title: place.name,
        position: place.geometry.location
      }));
      
      // center the circle on the first result
      if (index == 0) {
        circle.setCenter(place.geometry.location);
      }
      if (place.geometry.viewport) {
        // Only geocodes have viewport.
        bounds.union(place.geometry.viewport);
      } else {
        bounds.extend(place.geometry.location);
      }
    });
    map.fitBounds(bounds);
  });
}
google.maps.event.addDomListener(window, "load", initAutocomplete);
/* 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;
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry,places"></script>
<input id="pac-input" class="controls" type="text" placeholder="Search Box">
<div id="map"></div>

person geocodezip    schedule 21.01.2018
comment
Это действительно здорово. Спасибо. И спасибо, что ответили мне так быстро. Хорошего дня. Я отметил ваш ответ как успешный ответ на вопрос. Есть ли что-нибудь еще, что я могу сделать? Я не могу отметить это как полезное, так как я новичок... - person CGarden; 22.01.2018