Google Maps JavaScript API - Toggle Route Visibility Instead of Clearing It - javascript

I am using the Google Maps JavaScript API to display driving routes on a map.
I have this code that will clear the route from the map entirely:
directionsDisplayD.setDirections({routes: []});
Is there a way to instead just toggle its visibility?

Set the map property of the DirectionsRenderer object to null to hide the directions. Set it back to your map object to re-display the directions.
function initMap() {
var directionsService = new google.maps.DirectionsService;
var directionsDisplay = new google.maps.DirectionsRenderer;
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 7,
center: {
lat: 41.85,
lng: -87.65
}
});
directionsDisplay.setMap(map);
calculateAndDisplayRoute(directionsService, directionsDisplay);
google.maps.event.addDomListener(document.getElementById("btn"), 'click', function(evt) {
if (directionsDisplay.getMap() != null) directionsDisplay.setMap(null);
else directionsDisplay.setMap(map);
});
}
function calculateAndDisplayRoute(directionsService, directionsDisplay) {
directionsService.route({
origin: "New York, NY",
destination: "Trenton, NJ",
travelMode: 'DRIVING'
}, function(response, status) {
if (status === 'OK') {
directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
}
#floating-panel {
position: absolute;
top: 10px;
left: 25%;
z-index: 5;
background-color: #fff;
padding: 5px;
border: 1px solid #999;
text-align: center;
font-family: 'Roboto', 'sans-serif';
line-height: 30px;
padding-left: 10px;
}
<input id="btn" type="button" value="toggle" />
<div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script async defer src="https://maps.googleapis.com/maps/api/js?callback=initMap"></script>

Related

reverse geocoding without map

Using the below code to find local area from longitude and latitude, i'm not really wanting a specific address, just city or state.
The problem is that all I need is the city placed in to a variable, I dont want the map. Is this possible
I have taken this code from google developers site and put an alert box to display the address, which is fine, but dont want the map.
I have come across this which returns details from long/lat,
https://maps.googleapis.com/maps/api/geocode/json?
latlng=55.056499,1.600130&key=XXX&sensor=false
But getting this message - although not exceeding limit
{
"error_message" : "You have exceeded your daily request quota for this API. If
you did not set a custom daily request quota, verify your project has an
active billing account: http://g.co/dev/maps-no-account",
"results" : [],
"status" : "OVER_QUERY_LIMIT"
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Reverse Geocoding</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;
}
#floating-panel {
position: absolute;
top: 10px;
left: 25%;
z-index: 5;
background-color: #fff;
padding: 5px;
border: 1px solid #999;
text-align: center;
font-family: 'Roboto','sans-serif';
line-height: 30px;
padding-left: 10px;
}
#floating-panel {
position: absolute;
top: 5px;
left: 50%;
margin-left: -180px;
width: 350px;
z-index: 5;
background-color: #fff;
padding: 5px;
border: 1px solid #999;
}
#latlng {
width: 225px;
}
</style>
</head>
<body>
<div id="floating-panel">
<input id="latlng" type="text" value="40.714224,-73.961452">
<input id="submit" type="button" value="Reverse Geocode">
</div>
<div id="map"></div>
<script>
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 8,
center: {lat: 40.731, lng: -73.997}
});
var geocoder = new google.maps.Geocoder;
var infowindow = new google.maps.InfoWindow;
document.getElementById('submit').addEventListener('click',
function() {
geocodeLatLng(geocoder, map, infowindow);
});
}
function geocodeLatLng(geocoder, map, infowindow) {
var input = document.getElementById('latlng').value;
var latlngStr = input.split(',', 2);
var latlng = {lat: parseFloat(latlngStr[0]), lng:
parseFloat(latlngStr[1])};
geocoder.geocode({'location': latlng}, function(results, status) {
if (status === 'OK') {
if (results[0])
{
map.setZoom(11);
var marker = new google.maps.Marker({
position: latlng,
map: map
});
// infowindow.setContent(results[0].formatted_address);
// infowindow.open(map, marker);
window.alert(results[0].formatted_address);
}
else {
window.alert('No results found');
}
} else {
window.alert('Geocoder failed due to: ' + status);
}
});
}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=XX&callback=initMap">
</script>
</body>
</html>

Getting user's location for google Maps

So I'm trying to have google maps with direction service It works fine until I try to get the user's location to use as a start point. The idea is to give a user directions from their current location to one of the three. I have been following along with some guides on on Google's API.
When I try to get the user's location I try using:
if (navigator.geolocation) {
var position = navigator.geolocation.getCurrentPosition();
googleCoords = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
}
else {
alert("No geolocation!");
}
But for some reason this breaks the map? Trying to get the user's coordinates in a variable to use in the Directions services and as an origin for the map. Thanks
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Displaying text directions with <code>setPanel()</code></title>
<style>
#map {
height: 100%;
}
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#floating-panel {
position: absolute;
top: 10px;
left: 25%;
z-index: 5;
background-color: #fff;
padding: 5px;
border: 1px solid #999;
text-align: center;
font-family: 'Roboto','sans-serif';
line-height: 30px;
padding-left: 10px;
}
#right-panel {
font-family: 'Roboto','sans-serif';
line-height: 30px;
padding-left: 10px;
}
#right-panel select, #right-panel input {
font-size: 15px;
}
#right-panel select {
width: 100%;
}
#right-panel i {
font-size: 12px;
}
#right-panel {
height: 100%;
float: right;
width: 390px;
overflow: auto;
}
#map {
margin-right: 400px;
}
#floating-panel {
background: #fff;
padding: 5px;
font-size: 14px;
font-family: Arial;
border: 1px solid #ccc;
box-shadow: 0 2px 2px rgba(33, 33, 33, 0.4);
display: none;
}
#media print {
#map {
height: 500px;
margin: 0;
}
#right-panel {
float: none;
width: auto;
}
}
</style>
</head>
<body>
<div id="floating-panel">
<strong>Start:</strong>
<select id="start">
<option value="USERLOCATION">Your location</option>
</select>
<br>
<strong>End:</strong>
<select id="end">
<option value="memorial university of newfoundland">St. John's
Campus</option>
<option value="marine insitute of memorial university of
newfoundland">Marine Insitute</option>
<option value="grenfell campus">Grenfell Campus</option>
</select>
</div>
<div id="right-panel"></div>
<div id="map"></div>
<script>
var lat = null;
var long = null;
var googleCoords = null;
function initMap() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition();
googleCoords = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
}
else {
alert("No geolocation!");
}
var directionsDisplay = new google.maps.DirectionsRenderer;
var directionsService = new google.maps.DirectionsService;
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 7,
center: {lat: 41.85, lng: -87.65}
});
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById('right-panel'));
var control = document.getElementById('floating-panel');
control.style.display = 'block';
map.controls[google.maps.ControlPosition.TOP_CENTER].push(control);
var onChangeHandler = function() {
calculateAndDisplayRoute(directionsService, directionsDisplay);
};
document.getElementById('start').addEventListener('change',
onChangeHandler);
document.getElementById('end').addEventListener('change',
onChangeHandler);
}
function calculateAndDisplayRoute(directionsService, directionsDisplay) {
var start = document.getElementById('start').value;
var end = document.getElementById('end').value;
directionsService.route({
origin: start,
destination: end,
travelMode: 'DRIVING'
}, function(response, status) {
if (status === 'OK') {
directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=APIKEY&callback=initMap">
</script>
</body>
You must do into a function getCurrentPosition.
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
you should get the position from callback function like this.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position){
var googleCoords = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
});
} else {
alert("Geolocation is not supported by this browser.");
}

(Search option not working) Uncaught ReferenceError: google is not defined

I'm trying to implement the Google Maps API onto my website. Google Maps loads, however search option still seems to be at large due to the below error message
Uncaught ReferenceError: google is not defined
on following line:
var searchBox = new google.maps.places.SearchBox(input);
What is it that needs to be corrected to get this code going ?
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Places Searchbox</title>
<style>
#map {
width: 100%;
height: 400px;
background-color: #CCC;
}
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
}
.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);
}
#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: 300px;
}
#pac-input:focus {
border-color: #4d90fe;
}
.pac-container {
font-family: Roboto;
}
#type-selector {
color: #fff;
background-color: #4d90fe;
padding: 5px 11px 0px 11px;
}
#type-selector label {
font-family: Roboto;
font-size: 13px;
font-weight: 300;
}
#target {
width: 345px;
}
</style>
</head>
<body>
<div id="map"></div>
<input id="pac-input" class="controls" type="text" placeholder="Search Box">
<script>
function initMap() {
var mapDiv = document.getElementById('map');
var map = new google.maps.Map(mapDiv, {
center: {lat: 44.540, lng: -78.546},
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
}
// 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: google.maps.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.
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);
});
</script>
<script src="http://maps.googleapis.com/maps/api/js?v=3&sensor=false&callback=initMap" async defer></script>
</body>
</html>
Any help would be highly appreciated !!!
You are asynchronously loading the API. You need to put all the code that depends on the API in the callback function (initMap).
Also, you didn't read this comment, you aren't including the places library:
// 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">
proof of concept fiddle
code snippet:
function initMap() {
var mapDiv = document.getElementById('map');
var map = new google.maps.Map(mapDiv, {
center: {
lat: 44.540,
lng: -78.546
},
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
// 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: google.maps.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.
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);
});
}
#map {
width: 100%;
height: 400px;
background-color: #CCC;
}
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
}
.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);
}
#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: 300px;
}
#pac-input:focus {
border-color: #4d90fe;
}
.pac-container {
font-family: Roboto;
}
#type-selector {
color: #fff;
background-color: #4d90fe;
padding: 5px 11px 0px 11px;
}
#type-selector label {
font-family: Roboto;
font-size: 13px;
font-weight: 300;
}
#target {
width: 345px;
}
<script src="http://maps.googleapis.com/maps/api/js?v=3&libraries=places&callback=initMap" async defer></script>
<div id="map"></div>
<input id="pac-input" class="controls" type="text" placeholder="Search Box" />
Put whole your code to the initMap bc google will be defined only after Google Maps script will be loaded on the page.
Also added small verification to make it worked and no errors.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Places Searchbox</title>
<style>
#map {
width: 100%;
height: 400px;
background-color: #CCC;
}
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
}
.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);
}
#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: 300px;
}
#pac-input:focus {
border-color: #4d90fe;
}
.pac-container {
font-family: Roboto;
}
#type-selector {
color: #fff;
background-color: #4d90fe;
padding: 5px 11px 0px 11px;
}
#type-selector label {
font-family: Roboto;
font-size: 13px;
font-weight: 300;
}
#target {
width: 345px;
}
</style>
</head>
<body>
<div id="map"></div>
<input id="pac-input" class="controls" type="text" placeholder="Search Box">
<script>
function initMap() {
var mapDiv = document.getElementById('map');
var map = new google.maps.Map(mapDiv, {
center: {lat: 44.540, lng: -78.546},
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
// 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: google.maps.MapTypeId.ROADMAP
//});
// Create the search box and link it to the UI element.
var input = document.getElementById('pac-input');
if (!google.maps.places) {
return false;
}
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.
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);
});
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&callback=initMap" async defer></script>
</body>
</html>

Reverse Geocoding example doesn't display the street name of a location in some regions

This reverse geocoding code does not return the street name of a location in some areas (Example: {36.82687, 10.09948}), actually, I get only the name of the town and the country despite the fact that the name of the street is available on the map. I was wondering if there was a trick to get the streets' names in those regions?
Thanks for your help.
The example you reference returns the formatted_address of the 2nd entry ("[1]") in the results array. The most detailed entry is usually the 1st entry ("[0]"). If I change the code to use that, I get the street name.
proof of concept fiddle
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 8,
center: {
lat: 40.731,
lng: -73.997
}
});
var geocoder = new google.maps.Geocoder;
var infowindow = new google.maps.InfoWindow;
document.getElementById('submit').addEventListener('click', function() {
geocodeLatLng(geocoder, map, infowindow);
});
}
function geocodeLatLng(geocoder, map, infowindow) {
var input = document.getElementById('latlng').value;
var latlngStr = input.split(',', 2);
var latlng = {
lat: parseFloat(latlngStr[0]),
lng: parseFloat(latlngStr[1])
};
geocoder.geocode({
'location': latlng
}, function(results, status) {
if (status === google.maps.GeocoderStatus.OK) {
if (results[0]) {
map.setZoom(11);
var marker = new google.maps.Marker({
position: latlng,
map: map
});
infowindow.setContent(results[0].formatted_address);
infowindow.open(map, marker);
map.setCenter(latlng);
} else {
window.alert('No results found');
}
} else {
window.alert('Geocoder failed due to: ' + status);
}
});
}
google.maps.event.addDomListener(window, 'load', initMap);
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
}
#floating-panel {
position: absolute;
top: 10px;
left: 25%;
z-index: 5;
background-color: #fff;
padding: 5px;
border: 1px solid #999;
text-align: center;
font-family: 'Roboto', 'sans-serif';
line-height: 30px;
padding-left: 10px;
}
</style> <style> #floating-panel {
position: absolute;
top: 5px;
left: 50%;
margin-left: -180px;
width: 350px;
z-index: 5;
background-color: #fff;
padding: 5px;
border: 1px solid #999;
}
#latlng {
width: 225px;
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="floating-panel">
<input id="latlng" type="text" value="36.82687, 10.09948">
<input id="submit" type="button" value="Reverse Geocode">
</div>
<div id="map"></div>
If you really only want the street name, you should not depend on the entry in the results array, you should iterate through the results of the first (most exact) entry, looking for the address_component with type route
proof of concept fiddle
code snippet:
var marker;
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 8,
center: {
lat: 40.731,
lng: -73.997
}
});
var geocoder = new google.maps.Geocoder();
var infowindow = new google.maps.InfoWindow();
google.maps.event.addListener(map, 'click', function(evt) {
geocodeLatLng(evt.latLng, geocoder, map, infowindow);
});
document.getElementById('submit').addEventListener('click', function() {
geocodeLatLngForm(geocoder, map, infowindow);
});
}
function geocodeLatLngForm(geocoder, map, infowindow) {
var input = document.getElementById('latlng').value;
var latlngStr = input.split(',', 2);
var latlng = {
lat: parseFloat(latlngStr[0]),
lng: parseFloat(latlngStr[1])
};
geocodeLatLng(latlng, geocoder, map, infowindow);
}
function geocodeLatLng(latlng, geocoder, map, infowindow) {
geocoder.geocode({
'location': latlng
}, function(results, status) {
if (status === google.maps.GeocoderStatus.OK) {
if (results[0]) {
map.setZoom(15);
if (marker && marker.setMap) {
marker.setMap(null);
}
marker = new google.maps.Marker({
position: latlng,
map: map
});
map.setCenter(latlng);
// find the street name of the first entry
var street_name = "not available";
for (var i = 0; i < results[0].address_components.length; i++) {
for (var j = 0; j < results[0].address_components[i].types.length; j++) {
if (results[0].address_components[i].types[j] == "route") {
street_name = results[0].address_components[i].long_name;
break;
}
}
}
infowindow.setContent(street_name);
infowindow.open(map, marker);
} else {
window.alert('No results found');
}
} else {
window.alert('Geocoder failed due to: ' + status);
}
});
}
google.maps.event.addDomListener(window, 'load', initMap);
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
}
#floating-panel {
position: absolute;
top: 10px;
left: 25%;
z-index: 5;
background-color: #fff;
padding: 5px;
border: 1px solid #999;
text-align: center;
font-family: 'Roboto', 'sans-serif';
line-height: 30px;
padding-left: 10px;
}
</style> <style> #floating-panel {
position: absolute;
top: 5px;
left: 50%;
margin-left: -180px;
width: 350px;
z-index: 5;
background-color: #fff;
padding: 5px;
border: 1px solid #999;
}
#latlng {
width: 225px;
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="floating-panel">
<input id="latlng" type="text" value="36.82687, 10.09948">
<input id="submit" type="button" value="Reverse Geocode">
</div>
<div id="map"></div>

My google maps is cut off, I'm wondering why? Javascript, V

It's kinda hard to explain so I uploaded a screen shot of the issue:
As you can see, despite the div real-estate on the map (this is actual size), it only displays 1/6th of the map! This little widget can be resized but even when it is it is cut off. I'm sure I'm doing something wrong but can't figure it out. Here's the CSS code for the div that contains the map:
#map {
border-right-color: black;
border-left-color: black;
border-right-width: 1px;
border-left-width: 1px;
position: absolute;
margin-top: 0px;
top: 38px;
left: 0px;
width: auto;
height: auto;
right: 0px;
bottom: 10px;
background-color: rgb(204, 204, 204);
border-bottom-style: solid;
border-top-style: solid;
border-bottom-width: 1px;
border-top-width: 1px;
border-bottom-color: rgb(204, 204, 204);
border-top-color: rgb(204, 204, 204);
overflow: hidden;
}
here's the javascript that is making the map:
//google maps apis
var marker;
var setLocation = new google.maps.LatLng(59.32522, 18.07002);
var marker;
function placeMarker(location) {
if ( marker ) {
marker.setPosition(location);
} else {
marker = new google.maps.Marker({
position: location,
map: map,
draggable: true
});
}
}
function searchGoogleMaps(event) {
var address =event.target.value;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
placeMarker(results[0].geometry.location)
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
var geocoder;
var map;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(-34.397, 150.644);
var myOptions = {
zoom: 2,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map"), myOptions);
}
function toggleBounce() {
if (marker.getAnimation() != null) {
marker.setAnimation(null);
} else {
marker.setAnimation(google.maps.Animation.BOUNCE);
}
}
and finally the javascript file that is being called to make this all happen:
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?libraries=places&sensor=false"></script>
Thanks in advance, especially for taking the time to read a long question like this!
Whenever your 'map' div changes its sizes, you need to trigger 'resize' event explicitly on Google Maps component:
Developers should trigger this event on the map when the div changes
size: google.maps.event.trigger(map, 'resize') .
https://developers.google.com/maps/documentation/javascript/reference#Map

Categories