지도가없는 Google 장소 라이브러리
근처 검색 요청에 Google 장소 라이브러리를 사용하려고합니다. https://developers.google.com/maps/documentation/javascript/places#place_search_requests
json 응답을 가져 와서 html 목록에 넣고 싶습니다. 이제 결과를지도 나 다른 것에 표시하고 싶습니다. 지도를 전혀 사용하고 싶지 않습니다. 그러나 문서에는지도가 있어야한다고 명시되어 있습니다.
service = new google.maps.places.PlacesService(**map**);
PlacesService 함수의 인수로 전달합니다. 지금 내가하는 일은 height : 0의지도를 추가하는 것이지만 여전히 많은 양의 메모리를 소비합니다 (나는 sencha touch 2 앱을 개발하고 메모리가 중요합니다). 지도없이 주변 검색 요청을 사용하는 해결 방법이 있습니까? JSONP 요청을 지원하지 않으므로 Google Places API를 사용하고 싶지 않습니다.
문서화 된대로 PlacesService는 결과에 대한 속성을 렌더링 할지도 또는 노드 를 인수로받습니다 .
따라서 맵 대신 노드 (HTML 요소 인 노드) 만 사용하면됩니다.
참고 : 속성을 숨기는 것은 장소 정책을 위반하는 것입니다 (지도에 속성이 표시되므로 인수로 사용될 때지도를 숨 깁니다).
이것은 또한 당신에게 흥미로울 수 있습니다. Google Places API가 TOC를 위반합니까?
예 : 간단히 말해서
jQuery를 사용하는 경우 :
var service = new google.maps.places.PlacesService($('#tag-id').get(0));
일반 자바 스크립트 인 경우 :
var service = new google.maps.places.PlacesService(document.createElement('div'));
그런 다음 나머지 예제 코드를 사용하여 평소 와 같이 진행합니다 .
service.nearbySearch(request, callback);
예 : 반환 된 세부 정보 사용
참고 :이 예에서는 jQuery
.
<ul class="reviews__content" id="reviews__content">
</ul>
<div id="service-helper"></div>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=GOOGLE_API_KEY_HERE&libraries=places&callback=getRelevantGoogleReviews">
</script>
<script type="text/javascript">
window.getRelevantGoogleReviews = function(){
var service = new google.maps.places.PlacesService($('#service-helper').get(0)); // note that it removes the content inside div with tag '#service-helper'
service.getDetails({
placeId: 'ChIJAwEf5VFQqEcRollj8j_kqnE' // get a placeId using https://developers.google.com/places/web-service/place-id
}, function(place, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
var resultcontent = '';
for (i=0; i<place.reviews.length; ++i) {
//window.alert('Name:' + place.name + '. ID: ' + place.place_id + '. address: ' + place.formatted_address);
resultcontent += '<li class="reviews__item">'
resultcontent += '<div class="reviews__review-er">' + place.reviews[i].author_name + '</div>';
var reviewDate = new Date(place.reviews[i].time * 1000);
var reviewDateMM = reviewDate.getMonth() + 1;
var reviewDateFormatted = reviewDate.getDate() + '/' + reviewDateMM + '/' + reviewDate.getFullYear();
resultcontent += '<div class="reviews__review-date">' + reviewDateFormatted + '</div>';
resultcontent += '<div class="reviews__review-rating reviews__review-rating--' + place.reviews[i].rating +'"></div>';
if (!!place.reviews[i].text){
resultcontent += '<div class="reviews__review-comment">' + place.reviews[i].text + '</div>';
}
resultcontent += '</li>'
}
$('#reviews__content').append(resultcontent);
}
});
}
</script>
위의 댓글에서 Man이지도 를 초기화하지 않고 장소 서비스를 초기화하는 방법을 묻는 것을 보았습니다 . 그래서 여기에 추가 할 것이라고 생각했습니다.
placesService = new google.maps.places.PlacesService($('#predicted-places').get(0));
그래도 먼저 해당 ID로 html 요소를 만들어야합니다.
place_id에서 위치 데이터를 얻으려면 Geolocator 클래스를 사용하면됩니다. 여기 문서 . 이 클래스를 사용하면 place_id를 geocode () 메소드에 전달하고 좌표 및 기타 위치 데이터를 가져올 수 있습니다.
나는 같은 문제를 만났다.
Places Api가 이미 활성화 된 상태에서 Maps javascript Api를 사용하는 이유는이 간단한 작업에 대한 추가 비용입니까?
이 코드에서는 Maps Javascript API를 사용하지 않습니다. 모든 google.maps.Map API 메소드가 제거되었습니다. jsfiddle에서 잘 작동합니다 .
로컬 PC에서 작동하는지 확인하십시오. 대부분 로컬 PC 저장소에서 실행하고 Google API 콘솔에서 제공하는 제한된 요청을 사용하려고 할 때 403 오류가 발생합니다.
Google 개발자 콘솔에서 API 키를 가져 와서 코드의 스크립트 태그에있는 YOUR_API_KEY 슬롯에 삽입합니다. 여기에서 코드 를 실행하려고하지 마십시오. 당연히 API 키를 교체해야합니다.
// 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 initMap() {
var input = document.getElementById('pac-input');
var options = {
types: ['establishment']
};
var autocomplete = new google.maps.places.Autocomplete(input, options);
autocomplete.setFields(['place_id', 'geometry', 'name', 'formatted_address', 'formatted_phone_number', 'opening_hours', 'website', 'photos']);
autocomplete.addListener('place_changed', placechange);
function placechange() {
var place = autocomplete.getPlace();
var photos = place.photos;
document.getElementById('place_name').textContent = place.name;
document.getElementById('place_id').textContent = place.place_id;
document.getElementById('place_address').textContent = place.formatted_address;
document.getElementById('phone_no').textContent = place.formatted_phone_number;
document.getElementById('open_time').textContent = place.opening_hours.weekday_text[0];
document.getElementById('open_now').textContent = place.opening_hours.open_now;
document.getElementById('photo').src = photos[0].getUrl();
document.getElementById('photo').style = "width:50%;";
document.getElementById('website').textContent = place.website;
}
}
/* 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;
}
.controls {
background-color: #fff;
border-radius: 2px;
border: 1px solid transparent;
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
box-sizing: border-box;
font-family: Roboto;
font-size: 15px;
font-weight: 300;
height: 29px;
margin-left: 5px;
margin-top: 10px;
margin-bottom: 10px;
outline: none;
padding: 0 11px 0 13px;
text-overflow: ellipsis;
width: 400px;
}
.controls:focus {
border-color: #4d90fe;
}
.title {
font-weight: bold;
}
#infowindow-content {
display: none;
}
#map #infowindow-content {
display: inline;
}
<div>
<input id="pac-input" class="controls" type="text" placeholder="Enter a business">
</div>
<div id="info-table">
Name: <span id="place_name"></span><br> Place id: <span id="place_id"></span><br> Address :<span id="place_address"></span><br> Phone : <span id="phone_no"></span><br> Openhours: <span id="open_time"></span><br> Open Now : <span id="open_now"></span><br> website : <span id="website"></span><br> photo :<br> <img id="photo" src="" style="display:none;" />
</div>
<div id="map"></div>
<div id="infowindow-content">
<span id="place-name" class="title"></span><br>
<strong>Place ID:</strong> <span id="place-id"></span><br>
<span id="place-address"></span>
</div>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places&callback=initMap">
</script>
참고 URL : https://stackoverflow.com/questions/14343965/google-places-library-without-map
'programing tip' 카테고리의 다른 글
C # 값 / 객체는 언제 복사되고 언제 참조가 복사됩니까? (0) | 2020.11.22 |
---|---|
자바 스크립트 문자열 유형과 문자열 객체의 차이점은 무엇입니까? (0) | 2020.11.22 |
Pylint의 Cell-var-from-loop 경고 (0) | 2020.11.21 |
iFrame의 크기를 자동으로 조정하는 방법은 무엇입니까? (0) | 2020.11.21 |
형식화 된 메모리 뷰에 권장되는 메모리 할당 방법은 무엇입니까? (0) | 2020.11.21 |