2017-02-01 4 views
0

Я использую Google для поиска карт с помощью API карт Google Maps для получения нескольких результатов, таких как магазины и места и т. Д. .API-интерфейсы Google Maps - Как получить код страны, почтового индекса, номера, веб-сайта с помощью окна поиска карты Google по нескольким результатам

Он работает нормально, и я получаю адреса и широту - долготу, но как я могу получить остальную информацию, если доступна, например, страна, почтовый индекс, URL-адрес веб-сайта, номер контакта и рейтинги.

Вот мой код, любая помощь или предложение будут оценены.

<!DOCTYPE html> 
<html> 
    <head> 
     <script src="https://code.jquery.com/jquery-3.1.1.min.js" integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=" crossorigin="anonymous"></script> 
     <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=My_API_Key&libraries=places&callback=initAutocomplete" async defer"></script> 

     <style> 
     #wrapper {width:1280px; margin:0 auto;} 
      #map { 
       width: 100%; 
       height:300px; 
      } 
      .controls { 
       margin-top: 10px; 
       border: 1px solid transparent; 
       border-radius: 2px 0 0 2px; 
       box-sizing: border-box; 
       -moz-box-sizing: border-box; 
       height: 32px; 
       outline: none; 
       box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3); 
      } 
      #searchInput { 
       background-color: #fff; 
       font-family: Roboto; 
       font-size: 15px; 
       font-weight: 300; 
       margin-left: 12px; 
       padding: 0 11px 0 13px; 
       text-overflow: ellipsis; 
       width: 50%; 
      } 
      #searchInput:focus { 
       border-color: #4d90fe; 
      } 
      ul {margin:30px 100px;} 
      li {margin:5px 0;} 
      li span {font-weight:bold; padding-left:5px;} 
     </style> 
    </head> 
    <body> 
    <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. 

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

      // Create the search box and link it to the UI element. 
      var input = document.getElementById('searchInput'); 
      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 = []; 
      // [START region_getplaces] 
      // Listen for the event fired when the user selects a prediction and retrieve 
      // more details for that place. 
      searchBox.addListener('places_changed', function() { 

       $('#mapContent').html(""); 

       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) { 
        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. 
        var marker = new google.maps.Marker({ 
         map: map, 
         icon: icon, 
         title: place.name, 
         position: place.geometry.location 
        }); 
        google.maps.event.addListener(marker, 'click', function (evt) { 
         //document.getElementById('coordinates').value = marker.getPosition().toUrlValue(6); 
         alert(this.placeId) 
        }); 
        markers.push(marker); 
        if (place.geometry.viewport) { 
         // Only geocodes have viewport. 
         bounds.union(place.geometry.viewport); 
        } else { 
         bounds.extend(place.geometry.location); 
        } 

        $('#mapContent').append('<ul id="geoData">' + 
        '<li>Full Address: <span id="location">'+ place.formatted_address +'</span></li>'+ 
        '<li>Postal Code: <span id="postal_code"></span></li>'+ 
        '<li>Country: <span id="country">'+ +'</span></li>'+ 
        '<li>Latitude: <span id="lat">'+ place.geometry.location.lat() +'</span></li>'+ 
        '<li>Longitude: <span id="lon">'+ place.geometry.location.lng() +'</span></li>'+ 
        '<li>Website: <span id="website"></span></li>'+ 
        '<li>Contact Number: <span id="number"></span></li>'+ 
        '<li>Rating: <span id="rating"></span></li>'+ 
        '</ul>'); 



       }); 
       map.fitBounds(bounds); 
      }); 
      // [END region_getplaces] 
     } 

    </script> 
    <!--<input id="pac-input" class="controls" type="text" placeholder="Search Box"> 
    <div id="map"></div>--> 

     <div id=wrapper> 
      <input id="searchInput" class="controls" type="text" placeholder="Enter a location"> 
      <div id="map"></div> 
      <div id="mapContent"> 

      </div> 
     </div> 

    </body> 
</html> 

ответ

1

В Картах Google Maps вы найдете ссылку и идентификатор. Вы можете использовать этот идентификатор для запроса дополнительных сведений.

Я добавил это к своему коду:

// make sure this variable is accesible where you need it (scope) 
var service = new google.maps.places.PlacesService(map); 

затем, например, веб-сайт:

// request details 
service.getDetails(place, function(result, status) { 
    if (status !== google.maps.places.PlacesServiceStatus.OK) { 
    console.error(status); 
    return; 
    } 
    $('#website').html('<a target="_blank" href="'+ result.website +'">'+ result.website +'</a>'); 
}); 

Вы можете получить дополнительные детали, см https://developers.google.com/maps/documentation/javascript/places


Теперь, другой проблема, с которой вы сталкиваетесь, заключается в том, что идентификатор должен быть уникальным !!! Поэтому вы не должны ставить это в петлю foreach. Мое решение будет заполнять только в первом появлении Ид = «сайт»

places.forEach(function (place) { 
    ... 
    <span id="website"></span> 
    ... 
} 

Вы должны решить эту первую перед continueing. Используйте класс вместо идентификатора для всех вещей внутри для-петли


Вот полный скрипт

<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. 
    function initAutocomplete() { 
     var map = new google.maps.Map(document.getElementById('map'), { 
      center: { 
       lat: -33.8688, 
       lng: 151.2195 
      }, 
      zoom: 13, 
      mapTypeId: google.maps.MapTypeId.ROADMAP 
     }); 
     // Create the search box and link it to the UI element. 
     var input = document.getElementById('searchInput'); 
     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 = []; 
     // srvice for PLACE details 
     var service = new google.maps.places.PlacesService(map); 
     // [START region_getplaces] 
     // Listen for the event fired when the user selects a prediction and retrieve 
     // more details for that place. 
     searchBox.addListener('places_changed', function() { 
      $('#mapContent').html(""); 
      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) { 
       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. 
       var marker = new google.maps.Marker({ 
        map: map, 
        icon: icon, 
        title: place.name, 
        position: place.geometry.location 
       }); 
       google.maps.event.addListener(marker, 'click', function (evt) { 
        //document.getElementById('coordinates').value = marker.getPosition().toUrlValue(6); 
        alert(this.placeId) 
       }); 
       markers.push(marker); 
       if (place.geometry.viewport) { 
        // Only geocodes have viewport. 
        bounds.union(place.geometry.viewport); 
       } else { 
        bounds.extend(place.geometry.location); 
       } 
       $('#mapContent').append('<ul id="geoData">' + 
       '<li>Full Address: <span id="location">'+ place.formatted_address +'</span></li>'+ 
       '<li>Postal Code: <span id="postal_code"></span></li>'+ 
       '<li>Country: <span id="country">'+ +'</span></li>'+ 
       '<li>Latitude: <span id="lat">'+ place.geometry.location.lat() +'</span></li>'+ 
       '<li>Longitude: <span id="lon">'+ place.geometry.location.lng() +'</span></li>'+ 
       '<li>Website: <span id="website"></span></li>'+ 
       '<li>Contact Number: <span id="number"></span></li>'+ 
       '<li>Rating: <span id="rating"></span></li>'+ 
       '</ul>'); 
     // request details 
       service.getDetails(place, function(result, status) { 
        if (status !== google.maps.places.PlacesServiceStatus.OK) { 
        console.error(status); 
        return; 
        } 
        $('#website').html('<a target="_blank" href="'+ result.website +'">'+ result.website +'</a>'); 
       }); 
      }); 
      map.fitBounds(bounds); 
     }); 
     // [END region_getplaces] 
    } 
</script> 
+0

Благодаря Эммануэль, есть изменить свой код, как это было предложено, и есть все, что в итоге, действительно полезный человек. – Ajoshi

+0

Да, с удовольствием помогите –