В моем Java Spring MVC web application
я пытаюсь загрузить google map
с несколькими местоположениями и возможностью установить местоположение с помощью Places API
.
У меня есть следующий код:
<div class="map-search">
<div class="input-field">
<input type="text" name="searchNear" id="searchNear" value="" class="autocomplete" placeholder="Enter a location" autocomplete="off">
<label for="searchNear" class="searchNear active"></label>
<button id="memberSearch" class="btn btn-defaults btn-group search-btn"><i class="fa fa-search"></i></button>
</div>
У меня также есть следующие скрипты:
<script src="http://maps.google.com/maps/api/js?key=googleAPIKey&libraries=places&callback=initAutocomplete" async defer></script>
<script type="text/javascript" src="my-path/js/custom-scripts.js"></script>
Внутри моего custom-scripts.js у меня есть следующий код:
function initAutocomplete() {
$.getJSON('/smartwcm-web/get-locations', function(data)
{
const obj = data;
var locations = obj.locations.map(({info, latitude, longitude}) => [info, latitude, longitude]);
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: new google.maps.LatLng(33.0243206, -96.6745042),
mapTypeId: google.maps.MapTypeId.ROADMAP,
gestureHandling: 'greedy'
});
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map
});
google.maps.event.addListener(marker, 'mouseover', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
});
// Create the autocomplete object, restricting the search to geographical
// location types.
autocomplete = new google.maps.places.Autocomplete(
(document.getElementById("searchNear")),
{types: ["geocode"]});
// When the user selects an address from the dropdown, populate the address
// fields in the form.
autocomplete.addListener("place_changed", fillInAddress);
}
$(document).on( 'click','a[id^="showMap-"]', function(event) {
jQuery("#pageLoading").show();
event.preventDefault();
var arr = this.id.split('-');
var count = arr[1];
var latVal = +$("#lat-"+count).val();
var lonVal = +$("#lon-"+count).val();
var titleVal = $("#info-"+count).val();
var newCenter = {lat: latVal, lng: lonVal};
// The map, centered at newCenter
var map = new google.maps.Map(
document.getElementById('map'), {zoom: 4, center: newCenter, mapTypeId: google.maps.MapTypeId.ROADMAP,
gestureHandling: 'greedy'});
// The marker, positioned at newCenter
var marker = new google.maps.Marker({position: newCenter, map: map, title: titleVal});
jQuery("#pageLoading").hide();
});
if((jQuery("#searchNear").val()).length == 0)
{
if(jQuery("#userLocation").length)
{
jQuery("#searchNear").val(jQuery("#userLocation").val());
var cachedLoc = jQuery("#userLocation").val();
var loc_array = "";
if(cachedLoc.indexOf(',') != -1)
{
loc_array = cachedLoc.split(',');
}
else
{
loc_array = cachedLoc.split(' ');
}
jQuery("#postal_code").val('');
if(loc_array[2] && $.isNumeric(loc_array[2]))
{
jQuery("#postal_code").val(loc_array[2].trim());
}
}
}
var placeSearch, autocomplete;
var componentForm = {
street_number: "short_name",
route: "long_name",
locality: "long_name",
administrative_area_level_1: "short_name",
country: "long_name",
postal_code: "short_name"
};
/*function initAutocomplete() {
// Create the autocomplete object, restricting the search to geographical
// location types.
autocomplete = new google.maps.places.Autocomplete(
*//** @type {!HTMLInputElement} *//*(document.getElementById("searchNear")),
{types: ["geocode"]});
// When the user selects an address from the dropdown, populate the address
// fields in the form.
autocomplete.addListener("place_changed", fillInAddress);
}*/
function fillInAddress() {
// Get the place details from the autocomplete object.
var place = autocomplete.getPlace();
for (var component in componentForm) {
document.getElementById(component).value = "";
document.getElementById(component).disabled = false;
}
// Get each component of the address from the place details
// and fill the corresponding field on the form.
for (var i = 0; i < place.address_components.length; i++) {
var addressType = place.address_components[i].types[0];
if (componentForm[addressType]) {
var val = place.address_components[i][componentForm[addressType]];
document.getElementById(addressType).value = val;
}
}
}
Код работает в основном для меня, но иногда я получаю следующую ошибку:
Uncaught (в обещании) Ошибка: не удалось загрузить "maps_impl" Google Maps API с Javascript
Я не уверен, почемуэта ошибка происходит и не происходит всегда.Есть ли способ предотвратить это?