I have developed a Web application in which i use Goole Maps in my web application.
HTML:
<div id="showMap">
<input id="pac-input" class="controls" type="text" placeholder="Search Box">
<div id="map"></div>
</div>
<div id="errorMap">
<h1>No Map available due to Internet connectivity problems.</h1>
</div>
JS:
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 31.601043, lng: 74.169527},
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
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());
});
// 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) {
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);
});
loadMarkersDynamically(); // load markers function
}
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDwEvCr3alGTKBFt23yk4WVq5jg34I7CJs&libraries=places&callback=initMap" async defer></script>
Everything is working fine. But I have one problem when there is no internet connection then error come and map do not displayed. I want that if internet is not available then I want to hide showMap
div and show errorMap
div.
I have tried so many solutions: This, This and This from Stack Overflow but I am not able to solve my problem.
Maybe I am not calling function at right place that is provides in above answers, please tell me how to fix it.