I created a city specific film production company locator. I'm using the nearbySearch service with pagination of all places. Until that point everything is working fine.
Now I'm trying to add the getDetails service to display company info in an info window. Unfortanly I didn't figure out how to display an info window for each marker with the data from the getDetails service. I would be very thankful if someone can help me out to solve my problem! I put the code below!
var map;
var labels = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
var labelIndex = 0;
function initMap() {
// Create the map.
var duesseldorf = {lat: 51.2277, lng: 6.7735};
map = new google.maps.Map(document.getElementById('map'), {
center: duesseldorf,
zoom: 12
});
// Create the places service.
var service = new google.maps.places.PlacesService(map);
var getNextPage = null;
var moreButton = document.getElementById('more');
moreButton.onclick = function() {
moreButton.disabled = true;
if (getNextPage) getNextPage();
};
// Perform a nearby search.
service.nearbySearch(
{location: duesseldorf, radius: 14000, keyword: ['filmproduktion']},
function(results, status, pagination) {
if (status !== 'OK') return;
createMarkers(results);
moreButton.disabled = !pagination.hasNextPage;
getNextPage = pagination.hasNextPage && function() {
pagination.nextPage();
};
});
}
//display place details in info window
var request = {
placeId: 'ChIJN1t_tDeuEmsRUsoyG83frY4',
fields: ['name', 'formatted_address', 'place_id', 'geometry']
};
var infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.getDetails(request, function(place, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent('<div><strong>' + place.name + '</strong><br>' +
'Place ID: ' + place.place_id + '<br>' +
place.formatted_address + '</div>');
infowindow.open(map, this);
});
}
});
function createMarkers(places) {
var bounds = new google.maps.LatLngBounds();
var placesList = document.getElementById('places');
for (var i = 0, place; place = places[i]; i++) {
var image = {
url: 'https://developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png',
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)
};
var marker = new google.maps.Marker({
label: labels[labelIndex++ % labels.length],
map: map,
title: place.name,
position: place.geometry.location
});
var li = document.createElement('li');
li.textContent = place.name;
placesList.appendChild(li);
bounds.extend(place.geometry.location);
}
map.fitBounds(bounds);
}
google.maps.event.addDomListener(window, 'load', initialize);
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 620px;
width: 75%;
margin-left: 3%;
display: inline-block;
vertical-align: top;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
h1 {
text-align: center;
margin-top: 60px;
margin-bottom: 60px;
font-family: 'Roboto','sans-serif';
font-size: 40px;
}
#right-panel {
font-family: 'Roboto','sans-serif';
line-height: 30px;
padding: 10px;
}
#right-panel select, #right-panel input {
font-size: 15px;
}
#right-panel select {
width: 100%;
}
#right-panel i {
font-size: 12px;
}
#right-panel {
font-family: Arial, Helvetica, sans-serif;
position: absolute;
right: 3%;
height: 600px;
width: 300px;
z-index: 5;
border: 1px solid #999;
background: #fff;
display: inline-block;
vertical-align: top;
}
h2 {
font-size: 22px;
margin: 0 0 5px 0;
}
ul {
list-style-type: none;
padding: 0;
margin: 0;
height: 500px;
width: 300px;
overflow-y: scroll;
}
li {
background-color: #f1f1f1;
padding: 10px;
text-overflow: ellipsis;
white-space: nowrap;
overflow: hidden;
}
li:nth-child(odd) {
background-color: #fcfcfc;
}
#more {
width: 100%;
margin: 5px 0 0 0;
}
/* Media Queries */
#media(max-width: 768px){
#map{
display: block;
width: 90%;
margin: auto;
height: 300px;
}
#right-panel{
display: block;
margin: auto;
position: relative;
right: 0;
margin-top: 15px;
height: 400px;
}
ul{
height: 300px;
}
h1{
font-size: 30px;
margin-top: 40px;
margin-bottom: 40px;
}
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<link rel="stylesheet" href="./css/style.css">
<title>Place Search Pagination</title>
<script src="map.js"></script>
</head>
<header>
<h1>Die besten Filmproduktionen in Düsseldorf und Umgebung!</h1>
</header>
<body>
<div id="map"></div>
<div id="right-panel">
<h2>Filmproduktionen in Düsseldorf</h2>
<ul id="places"></ul>
<button id="more">Mehr Ergebnisse</button>
</div>
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places&callback=initMap" async defer></script>
</body>
</html>
I get a javascript error with the posted code: Uncaught ReferenceError: google is not defined on this line: var infowindow = new google.maps.InfoWindow();, because that is outside of initMap so executes before the API is loaded. Make it global (var infowindow;), then initialize it inside initMap.
var infowindow;
function initMap() {
infowindow = new google.maps.InfoWindow();
Then to open the details in the infowindow, call the getDetails request when the marker is clicked, opening the infowindow when the response comes back, keeping track of the reference to the marker from the click event (the var that=this; line, that gives you function closure on that so it is available when the response comes back to the getDetails request):
google.maps.event.addListener(marker, 'click', function(e) {
//display place details in info window
var request = {
placeId: this.place_id,
fields: ['name', 'formatted_address', 'place_id', 'geometry']
};
var service = new google.maps.places.PlacesService(map);
var that = this;
service.getDetails(request, function(place, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
infowindow.setContent('<div><strong>' + place.name + '</strong><br>' +
'Place ID: ' + place.place_id + '<br>' +
place.formatted_address + '</div>');
infowindow.open(map, that);
}
});
});
var map;
var labels = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
var labelIndex = 0;
var infowindow;
function initMap() {
// Create the map.
var duesseldorf = {
lat: 51.2277,
lng: 6.7735
};
map = new google.maps.Map(document.getElementById('map'), {
center: duesseldorf,
zoom: 12
});
infowindow = new google.maps.InfoWindow();
// Create the places service.
var service = new google.maps.places.PlacesService(map);
var getNextPage = null;
var moreButton = document.getElementById('more');
moreButton.onclick = function() {
moreButton.disabled = true;
if (getNextPage) getNextPage();
};
// Perform a nearby search.
service.nearbySearch({
location: duesseldorf,
radius: 14000,
keyword: ['filmproduktion']
},
function(results, status, pagination) {
if (status !== 'OK') return;
createMarkers(results);
moreButton.disabled = !pagination.hasNextPage;
getNextPage = pagination.hasNextPage && function() {
pagination.nextPage();
};
});
}
function createMarkers(places) {
var bounds = new google.maps.LatLngBounds();
var placesList = document.getElementById('places');
for (var i = 0, place; place = places[i]; i++) {
var image = {
url: 'https://developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png',
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)
};
var marker = new google.maps.Marker({
label: labels[labelIndex++ % labels.length],
map: map,
place_id: place.place_id,
title: place.name,
position: place.geometry.location
});
google.maps.event.addListener(marker, 'click', function(e) {
//display place details in info window
var request = {
placeId: this.place_id,
fields: ['name', 'formatted_address', 'place_id', 'geometry']
};
var service = new google.maps.places.PlacesService(map);
var that = this;
service.getDetails(request, function(place, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
infowindow.setContent('<div><strong>' + place.name + '</strong><br>' +
'Place ID: ' + place.place_id + '<br>' +
place.formatted_address + '</div>');
infowindow.open(map, that);
}
});
});
var li = document.createElement('li');
li.textContent = place.name;
placesList.appendChild(li);
bounds.extend(place.geometry.location);
}
map.fitBounds(bounds);
}
google.maps.event.addDomListener(window, 'load', initialize);
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 620px;
width: 75%;
margin-left: 3%;
display: inline-block;
vertical-align: top;
}
/* Optional: Makes the sample page fill the window. */
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
h1 {
text-align: center;
margin-top: 60px;
margin-bottom: 60px;
font-family: 'Roboto', 'sans-serif';
font-size: 40px;
}
#right-panel {
font-family: 'Roboto', 'sans-serif';
line-height: 30px;
padding: 10px;
}
#right-panel select,
#right-panel input {
font-size: 15px;
}
#right-panel select {
width: 100%;
}
#right-panel i {
font-size: 12px;
}
#right-panel {
font-family: Arial, Helvetica, sans-serif;
position: absolute;
right: 3%;
height: 600px;
width: 300px;
z-index: 5;
border: 1px solid #999;
background: #fff;
display: inline-block;
vertical-align: top;
}
h2 {
font-size: 22px;
margin: 0 0 5px 0;
}
ul {
list-style-type: none;
padding: 0;
margin: 0;
height: 500px;
width: 300px;
overflow-y: scroll;
}
li {
background-color: #f1f1f1;
padding: 10px;
text-overflow: ellipsis;
white-space: nowrap;
overflow: hidden;
}
li:nth-child(odd) {
background-color: #fcfcfc;
}
#more {
width: 100%;
margin: 5px 0 0 0;
}
/* Media Queries */
#media(max-width: 768px) {
#map {
display: block;
width: 90%;
margin: auto;
height: 300px;
}
#right-panel {
display: block;
margin: auto;
position: relative;
right: 0;
margin-top: 15px;
height: 400px;
}
ul {
height: 300px;
}
h1 {
font-size: 30px;
margin-top: 40px;
margin-bottom: 40px;
}
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<link rel="stylesheet" href="./css/style.css">
<title>Place Search Pagination</title>
<script src="map.js"></script>
</head>
<header>
<h1>Die besten Filmproduktionen in Düsseldorf und Umgebung!</h1>
</header>
<body>
<div id="map"></div>
<div id="right-panel">
<h2>Filmproduktionen in Düsseldorf</h2>
<ul id="places"></ul>
<button id="more">Mehr Ergebnisse</button>
</div>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&libraries=places&callback=initMap" async defer></script>
</body>
</html>
Related
For a project I'm currently working on, I'm looking to incorporate both elements of Google places to search with google street view, essentially forcing the location (after searching) to view as street/pano.
Google has a pretty solid 'basic' version but I can't seem to force it to use street view. Any insight would be awesome.
https://developers.google.com/maps/documentation/javascript/examples/places-searchbox
https://www.instantstreetview.com/ - Seems to do a pretty good job of it, but I can't seem to find any documentation regarding both.
Combine the code from the SearchBox example, with the StreetView example, should give you a first cut.
Probably more what you are looking for would be to combine the answer to this related question: Facing the targeted building with Google StreetView, with the SearchBox example
proof of concept fiddle
code snippet:
// 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">
var panorama;
var clickedMarker;
function initAutocomplete() {
var map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: -33.8688,
lng: 151.2195
},
zoom: 13,
mapTypeId: 'roadmap'
});
var sv = new google.maps.StreetViewService();
// 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, index) {
if (!place.geometry) {
console.log("Returned place contains no geometry");
return;
}
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
});
markers.push(marker);
google.maps.event.addListener(marker, 'click', function(e) {
clickedMarker = this;
sv.getPanoramaByLocation(marker.getPosition(), 50, processSVData);
});
if (place.geometry.viewport) {
// Only geocodes have viewport.
bounds.union(place.geometry.viewport);
} else {
bounds.extend(place.geometry.location);
}
});
map.fitBounds(bounds);
google.maps.event.trigger(markers[0], 'click');
});
}
function processSVData(data, status) {
if (status == google.maps.StreetViewStatus.OK) {
panorama = new google.maps.StreetViewPanorama(document.getElementById("pano"));
panorama.setPano(data.location.pano);
var camera = new google.maps.Marker({
position: data.location.latLng,
map: map,
draggable: true,
title: "camera"
});
var heading = google.maps.geometry.spherical.computeHeading(data.location.latLng, clickedMarker.getPosition());
document.getElementById('info').innerHTML = "heading:" + heading + "<br>" +
"location: " + clickedMarker.getPosition().toUrlValue(6) + "<br>" +
"camera:" + data.location.latLng.toUrlValue(6) + "<br>";
// alert(data.location.latLng+":"+myLatLng+":"+heading);
panorama.setPov({
heading: heading,
pitch: 0,
zoom: 1
});
panorama.setVisible(true);
} else {
alert("Street View data not found for this location.");
}
}
html,
body {
height: 100%;
margin: 0px;
padding: 0px;
}
#map,
#pano {
float: left;
height: 100%;
width: 45%;
}
#description {
font-family: Roboto;
font-size: 15px;
font-weight: 300;
}
#infowindow-content .title {
font-weight: bold;
}
#infowindow-content {
display: none;
}
#map #infowindow-content {
display: inline;
}
.pac-card {
margin: 10px 10px 0 0;
border-radius: 2px 0 0 2px;
box-sizing: border-box;
-moz-box-sizing: border-box;
outline: none;
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
background-color: #fff;
font-family: Roboto;
}
#pac-container {
padding-bottom: 12px;
margin-right: 12px;
}
.pac-controls {
display: inline-block;
padding: 5px 11px;
}
.pac-controls label {
font-family: Roboto;
font-size: 13px;
font-weight: 300;
}
#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: 400px;
}
#pac-input:focus {
border-color: #4d90fe;
}
#title {
color: #fff;
background-color: #4d90fe;
font-size: 25px;
font-weight: 500;
padding: 6px 12px;
}
#target {
width: 345px;
}
<input id="pac-input" class="controls" type="text" placeholder="Search Box">
<div id="map"></div>
<div id="pano"></div>
<div id="info"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&libraries=places&callback=initAutocomplete" async defer></script>
I created a places search google map that likes to search for places like types of schools, I made a marker for both private and public, the search box works, but when I click enter, It does not show the public/private schools, Is this because of my code? on icon? or marker?
The only problem is when I click enter, It does not display its markers
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Places Search Box</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;
}
#description {
font-family: Roboto;
font-size: 15px;
font-weight: 300;
}
#infowindow-content .title {
font-weight: bold;
}
#infowindow-content {
display: none;
}
#map #infowindow-content {
display: inline;
}
.pac-card {
margin: 10px 10px 0 0;
border-radius: 2px 0 0 2px;
box-sizing: border-box;
-moz-box-sizing: border-box;
outline: none;
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
background-color: #fff;
font-family: Roboto;
}
#pac-container {
padding-bottom: 12px;
margin-right: 12px;
}
.pac-controls {
display: inline-block;
padding: 5px 11px;
}
.pac-controls label {
font-family: Roboto;
font-size: 13px;
font-weight: 300;
}
#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: 400px;
}
#pac-input:focus {
border-color: #4d90fe;
}
#title {
color: #fff;
background-color: #4d90fe;
font-size: 25px;
font-weight: 500;
padding: 6px 12px;
}
#target {
width: 345px;
}
</style>
</head>
<body>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&libraries=places"></script>
<input id="pac-input" class="controls" type="text" placeholder="Search Box">
<div id="map"></div>
<script>
function initAutocomplete() {
var map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: -33.8688,
lng: 151.2195
},
zoom: 13,
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) {
if (!place.geometry) {
console.log("Returned place contains no geometry");
return;
}
var icons = {
'Public school': {
icon: 'http://i68.tinypic.com/xcnnz4.png'
},
'Private school': {
icon: 'http://i67.tinypic.com/2utkz8k.png'
}
};
// 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);
});
}
initAutocomplete();
</script>
</body>
</html>
Icon is not declared. You need to check the input to see if Private or Public school was entered and then set the icon accordingly.
// Create a marker for each place.
var marker = new google.maps.Marker({
map: map,
title: place.name,
position: place.geometry.location
});
if(place.name.toLowerCase() === 'private school') {
marker.setIcon('http://i67.tinypic.com/2utkz8k.png');
}
else if(place.name.toLowerCase() === 'public school') {
marker.setIcon('http://i68.tinypic.com/xcnnz4.png');
}
markers.push(marker);
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.");
}
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>
i need to make a restaurant finder.. but to do that i need to be able to locate my users.. i have been having a hard time figuring out on how to geolocate them and pinpoint their location on the map and find restaurants near them..please help me.. i am new to this
First js code
var map, places, iw;
var markers = [];
var searchTimeout;
var centerMarker;
var autocomplete;
var hostnameRegexp = new RegExp('^https?://.+?/');
function initialize() {
var myLatlng = new google.maps.LatLng(37.786906, -122.410156);
var myOptions = {
zoom: 15,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById('map_canvas'), myOptions);
places = new google.maps.places.PlacesService(map);
google.maps.event.addListener(map, 'tilesloaded', tilesLoaded);
document.getElementById('keyword').onkeyup = function(e) {
if (!e) var e = window.event;
if (e.keyCode != 13) return;
document.getElementById('keyword').blur();
search(document.getElementById('keyword').value);
}
var typeSelect = document.getElementById('type');
typeSelect.onchange = function() {
search();
};
var rankBySelect = document.getElementById('rankBy');
rankBySelect.onchange = function() {
search();
};
}
function tilesLoaded() {
search();
google.maps.event.clearListeners(map, 'tilesloaded');
google.maps.event.addListener(map, 'zoom_changed', searchIfRankByProminence);
google.maps.event.addListener(map, 'dragend', search);
}
function searchIfRankByProminence() {
if (document.getElementById('rankBy').value == 'prominence') {
search();
}
}
function search() {
clearResults();
clearMarkers();
if (searchTimeout) {
window.clearTimeout(searchTimeout);
}
searchTimeout = window.setTimeout(reallyDoSearch, 500);
}
function reallyDoSearch() {
var type = document.getElementById('type').value;
var keyword = document.getElementById('keyword').value;
var rankBy = document.getElementById('rankBy').value;
var search = {};
if (keyword) {
search.keyword = keyword;
}
if (type != 'establishment') {
search.types = [type];
}
if (rankBy == 'distance' && (search.types || search.keyword)) {
search.rankBy = google.maps.places.RankBy.DISTANCE;
search.location = map.getCenter();
centerMarker = new google.maps.Marker({
position: search.location,
animation: google.maps.Animation.DROP,
map: map
});
} else {
search.bounds = map.getBounds();
}
places.search(search, function(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
var icon = 'number_' + (i + 1) + '.png';
markers.push(new google.maps.Marker({
position: results[i].geometry.location,
animation: google.maps.Animation.DROP,
icon: icon
}));
google.maps.event.addListener(markers[i], 'click', getDetails(results[i], i));
window.setTimeout(dropMarker(i), i * 100);
addResult(results[i], i);
}
}
});
}
function clearMarkers() {
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(null);
}
markers = [];
if (centerMarker) {
centerMarker.setMap(null);
}
}
function dropMarker(i) {
return function() {
if (markers[i]) {
markers[i].setMap(map);
}
}
}
function addResult(result, i) {
var results = document.getElementById('results');
var tr = document.createElement('tr');
tr.style.backgroundColor = (i % 2 == 0 ? '#F0F0F0' : '#FFFFFF');
tr.onclick = function() {
google.maps.event.trigger(markers[i], 'click');
};
var iconTd = document.createElement('td');
var nameTd = document.createElement('td');
var icon = document.createElement('img');
icon.src = 'number_' + (i + 1) + '.png';
icon.setAttribute('class', 'placeIcon');
icon.setAttribute('className', 'placeIcon');
var name = document.createTextNode(result.name);
iconTd.appendChild(icon);
nameTd.appendChild(name);
tr.appendChild(iconTd);
tr.appendChild(nameTd);
results.appendChild(tr);
}
function clearResults() {
var results = document.getElementById('results');
while (results.childNodes[0]) {
results.removeChild(results.childNodes[0]);
}
}
function getDetails(result, i) {
return function() {
places.getDetails({
reference: result.reference
}, showInfoWindow(i));
}
}
function showInfoWindow(i) {
return function(place, status) {
if (iw) {
iw.close();
iw = null;
}
if (status == google.maps.places.PlacesServiceStatus.OK) {
iw = new google.maps.InfoWindow({
content: getIWContent(place)
});
iw.open(map, markers[i]);
}
}
}
function getIWContent(place) {
var content = '';
content += '<table>';
content += '<tr class="iw_table_row">';
content += '<td style="text-align: left"><img class="hotelIcon" src="' + place.icon + '"/></td>';
content += '<td><b>' + place.name + '</b></td></tr>';
content += '<tr class="iw_table_row"><td class="iw_attribute_name">Address:</td><td>' + place.vicinity + '</td></tr>';
if (place.formatted_phone_number) {
content += '<tr class="iw_table_row"><td class="iw_attribute_name">Telephone:</td><td>' + place.formatted_phone_number + '</td></tr>';
}
if (place.rating) {
var ratingHtml = '';
for (var i = 0; i < 5; i++) {
if (place.rating < (i + 0.5)) {
ratingHtml += '✩';
} else {
ratingHtml += '✭';
}
}
content += '<tr class="iw_table_row"><td class="iw_attribute_name">Rating:</td><td><span id="rating">' + ratingHtml + '</span></td></tr>';
}
if (place.website) {
var fullUrl = place.website;
var website = hostnameRegexp.exec(place.website);
if (website == null) {
website = 'http://' + place.website + '/';
fullUrl = website;
}
content += '<tr class="iw_table_row"><td class="iw_attribute_name">Website:</td><td>' + website + '</td></tr>';
}
content += '</table>';
return content;
}
google.maps.event.addDomListener(window, 'load', initialize);
<!-- begin snippet: js hide: false -->
html {
background: linear-gradient(rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url(superb-seaside-restaurant-hd-wallpaper-506329.jpg) no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
background-size: cover;
background-size: cover
}
#form {
font: 20px"Walkway SemiBold";
letter-spacing: 5px;
text-align: center;
padding-bottom: 3px;
padding-right: 4px;
padding-top: 3px;
height: 35%;
width: 50%;
background: #ccc;
margin-bottom: 10px;
/* Fallback for older browsers without RGBA-support */
background: rgba(204, 204, 204, 0.5);
float: left;
}
#header {
font: 20px"Josefin Slab";
letter-spacing: 10px;
background-color: #fff;
color: #000;
text-align: center;
margin-top: 3px;
padding: 5px;
width: 1255px;
background: #ccc;
margin-bottom: 10px;
/* Fallback for older browsers without RGBA-support */
background: rgba(204, 204, 204, 0.5);
}
#map_canvas {
-webkit-box-shadow: 0 0 10px #bfdeff;
-moz-box-shadow: 0 0 5px #bfdeff;
box-shadow: 0 0 7px #bfdeff;
float: right;
height: 500px;
width: 593px;
padding: 10px;
margin-right: 3px;
vertical-align: top;
}
#listing {
font: 18pt"Nilland";
letter-spacing: 5px;
text-align: center;
padding: 3px;
height: 500px;
width: 50%;
background: #ccc;
margin-bottom: 10px;
/* Fallback for older browsers without RGBA-support */
background: rgba(204, 204, 204, 0.5);
float: left;
}
#footer {
font: 18px"Nilland-Black";
letter-spacing: 10px;
background-color: #fff;
color: #000;
text-align: right;
padding: 5px;
height: 27px;
width: 1255px;
background: #ccc;
margin-top: 3px;
margin-bottom: 3px;
/* Fallback for older browsers without RGBA-support */
background: rgba(204, 204, 204, 0.5);
float: right;
}
.placeIcon {
width: 32px;
height: 37px;
margin: 4px;
}
.hotelIcon {
width: 24px;
height: 24px;
}
#resultsTable {
font: 16pt"Nilland-Black";
border-collapse: collapse;
width: 450px;
margin-left: 90px;
float: left;
background: rgba(204, 204, 204, 0.5);
}
#rating {
font-size: 13px;
font-family: Arial Unicode MS;
}
#keywordsLabel {
text-align: right;
width: 70px;
font-size: 14px;
padding: 4px;
position: absolute;
}
.iw_table_row {
height: 18px;
}
.iw_attribute_name {
font-weight: bold;
text-align: right;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>Map</title>
<link href="working.css" rel="stylesheet" type="text/css" />
<script src="http://maps.google.com/maps/api/js?sensor=true&libraries=places"></script>
<script src="C:\Users\beesumbernice\Documents\html\html\whole.js"></script>
<script src="C:\Users\beesumbernice\Documents\html\html\this.js"></script>
</head>
<body>
<div id="header">
<h1>
HEADER
</h1>
</div>
<div id="form">
Keywords:
<input id="keyword" type="text" placeholder="Mexican,Italian,Chinese..." />
<div id="controls">
<span id="typeLabel">
Type:
</span>
<select id="type">
<option value="bar">Bars</option>
<option value="cafe">Cafe</option>
<option value="restaurant" selected="selected">Restaurants</option>
</select>
<span id="rankByLabel">
Rank by:
</span>
<select id="rankBy">
<option value="prominence">Prominence</option>
<option value="distance" selected="selected">Distance</option>
</select>
</div>
</div>
<div id="map_canvas"></div>
<div id="listing" style="overflow-y: scroll; height:453px;">
<table id="resultsTable">
<tbody id="results"></tbody>
</table>
</div>
<div id="footer">
Maps Icons Collection
<img src="C:\Users\beesumbernice\Documents\html\html\desktop\powered-by-google-on-non-white.png" height="16" width="104"></img>
</div>
</body>
</html>
Hope this code will help you out
var mapInterval;
if(navigator.geolocation) {
var intervalTime = 5; // 5 seconds inteerval
mapInterval = window.setInterval(function(){
navigator.geolocation.getCurrentPosition(function(position) {
map.setCenter(new google.maps.LatLng(position.coords.latitude, position.coords.longitude));
}, intervalTime*1000)
});
// Whenever you want to stop updating the location
// mapInterval
Try this:
<html>
<body>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=places"></script>
<script>
function initialize(){
var mapOptions =
{
mapTypeId: google.maps.MapTypeId.ROADMAP,
zoom: 8
};
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var lat=position.coords.latitude;
var lng=position.coords.longitude;
var geolocate = new google.maps.LatLng(lat, lng);
map.setCenter(geolocate);
});
}
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<div id="map-canvas" style="width:300;height:300px;border:1px solid black;"> </div>
</body>
</html>
Check it out "HERE"