I use "Bootstrap v3.3.5 (http://getbootstrap.com)
Copyright 2011-2015 Twitter, Inc. " for my site and i want to add google-map. I run this code, and all maps is grey. I dont understand why this not work with modal. Can someone help me?
I also have included <script src="https://maps.googleapis.com/maps/api/js"></script>.
HTML:
<body>
<a class="openmodal" href="#contact" data-toggle="modal" data-id="Peggy Guggenheim Collection - Venice">Contact</a>
<div class="modal fade" id="contact" role="dialog">
<div class="modal-dialog modal-lg">
<div class="modal-content" id="back">
<div class="modal-header">
<h4>Contact<h4>
</div>
<div class="modal-body">
<div id="map"></div>
</div>
<div class="modal-footer">
<a class="btn btn-default" data-dismiss="modal">Close</a>
</div>
</div>
</div>
JS:
<script src="https://maps.googleapis.com/maps/api/js"></script>
<script>
function initialize() {
var mapCanvas = document.getElementById('map');
var mapOptions = {
center: new google.maps.LatLng(44.5403, -78.5463),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(mapCanvas, mapOptions)
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
CSS:
#map {
width: 500px;
height: 400px;
}
Here is the code above in a working fiddle -> http://jsfiddle.net/wgur1z7n/ (bootstrap 3.3.5)
Trigger the google maps resize event after the modal is shown :
$('#contact').on('shown.bs.modal', function () {
google.maps.event.trigger(map, "resize");
});
Triggering "resize" did not work for me. The map showed up, but with wrong coordinates and wrong zoom level. You probably have an initMap function on your page. This worked for me:
<script>
$('#myModal').on('shown.bs.modal', function () {
initMap();
});
</script>
Try this rookie solution
<!DOCTYPE html>
<html>
<head>
<title>Place Autocomplete</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=yes">
<meta charset="utf-8">
<style>
#map {
height: 450px;
width: 1080px;
}
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
.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;
}
.modal {
display: block;
z-index: 1;
padding-top: 20px;
padding-bottom: 20px width: 100%;
height: 100%;
overflow: auto;
background-color: rgb(0, 0, 0);
background-color: rgba(0, 0, 0, 0.4);
}
.modal-content {
background-color: #fefefe;
margin-left: 60px;
margin-bottom: 20px;
padding: 0;
border: 1px solid #888;
width: 90%;
height: 90%;
box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
-webkit-animation-name: animatetop;
-webkit-animation-duration: 4s;
animation-name: animatetop;
animation-duration: 4s
}
#-webkit-keyframes animatetop {
from {
top: -900px;
opacity: 0
}
to {
top: 0;
opacity: 1
}
}
#keyframes animatetop {
from {
top: -900px;
opacity: 0
}
to {
top: 0;
opacity: 1
}
}
.close {
color: white;
float: right;
font-size: 40px;
font-weight: bold;
margin-top: 10px;
}
.close:hover,
.close:focus {
color: #000;
text-decoration: none;
cursor: pointer;
}
.modal-header {
padding: 2px 16px;
background-color: #a8c9ff;
color: white;
}
.modal-body {
padding: 2px 16px;
background-color: white;
color: black;
}
.modal-footer {
padding: 2px 16px;
background-color: #a8c9ff;
color: white;
}
</style>
</head>
<body onload="clr()">
<div>
<div id='myModal' class='modal'>
<div class='modal-content'>
<div class='modal-header'>
<span onclick='cl()' class='close' style="border: 2px; border-color: black">OK</span>
<h2>Search location and click OK</h2>
<h4 style="color: red">Note : If map dosen't load propery Click here! (Click on location to select or Drag marker to position.)</h4></div>
<div class='modal-body'>
<input id="pac-input" class="controls" type="text" placeholder="Enter a location">
<div id="type-selector" class="controls">
<input type="radio" name="type" id="changetype-all">
<label for="changetype-all">All</label>
<input type="radio" name="type" id="changetype-establishment">
<label for="changetype-establishment">Establishments</label>
<input type="radio" name="type" id="changetype-address">
<label for="changetype-address">Addresses</label>
<input type="radio" name="type" id="changetype-geocode" checked="checked">
<label for="changetype-geocode">Geocodes</label>
</div>
<div id="map" style="position: none"></div>
</div>
<div class='modal-footer'></div>
</div>
</div>
<div style="">
<input type="button" onclick="notifi()" id="btn" value="Show map">
<input type="text" style="width: 400px" id="Location" placeholder="Choose location from map..." disabled="">
</div>
</div>
<script>
function initMap() {
var $Location = document.getElementById('Location');
var map = new google.maps.Map(document.getElementById('map'), {
center: { lat: -33.8688, lng: 151.2195 },
zoom: 13
});
google.maps.event.trigger(map, 'resize');
var input = /** #type {!HTMLInputElement} */ (
document.getElementById('pac-input'));
var types = document.getElementById('type-selector');
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
map.controls[google.maps.ControlPosition.TOP_LEFT].push(types);
var autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.bindTo('bounds', map);
var infowindow = new google.maps.InfoWindow();
var marker = new google.maps.Marker({
map: map,
anchorPoint: new google.maps.Point(0, -29),
draggable: true
});
autocomplete.addListener('place_changed', function() {
infowindow.close();
marker.setVisible(false);
var place = autocomplete.getPlace();
if (!place.geometry) {
window.alert("No details available for input: '" + place.name + "'");
return;
}
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(17);
}
marker.setIcon( /** #type {google.maps.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(35, 35)
}));
marker.setPosition(place.geometry.location);
marker.setVisible(true);
$Location.value = "Latitude : " + place.geometry.location.lat() + " Longitude : " + place.geometry.location.lng();
google.maps.event.addListener(marker, 'dragend', function(marker) {
var latLng = marker.latLng;
$Location.value = "Latitude : " + latLng.lat() + " Longitude : " + latLng.lng();
});
google.maps.event.addListener(marker, 'click', function(event) {
$Location.value = "Latitude : " + this.getPosition().lat() + " Longitude : " + this.getPosition().lng();
});
var address = '';
if (place.address_components) {
address = [
(place.address_components[0] && place.address_components[0].short_name || ''),
(place.address_components[1] && place.address_components[1].short_name || ''),
(place.address_components[2] && place.address_components[2].short_name || '')
].join(' ');
}
infowindow.setContent('<div><strong>' + place.name + '</strong><br>' + address);
infowindow.open(map, marker);
});
map.addListener('click', function(e) {
setTimeout(function() { marker.setPosition(e.latLng); }, 10);
$Location.value = "Latitude : " + e.latLng.lat() + " Longitude : " + e.latLng.lng();
google.maps.event.addListener(marker, 'click', function(event) {
$Location.value = "Latitude : " + this.getPosition().lat() + " Longitude : " + this.getPosition().lng();
});
});
marker.addListener('click', function() {
map.setCenter(marker.getPosition());
});
function setupClickListener(id, types) {
var radioButton = document.getElementById(id);
radioButton.addEventListener('click', function() {
autocomplete.setTypes(types);
});
}
setupClickListener('changetype-all', []);
setupClickListener('changetype-address', ['address']);
setupClickListener('changetype-establishment', ['establishment']);
setupClickListener('changetype-geocode', ['geocode']);
}
</script>
<script type="text/javascript">
var modal = document.getElementById('myModal');
var span = document.getElementsByClassName("close")[0];
span.onclick = function() {
modal.style.display = "none";
}
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
function cl() {
modal.style.display = "none";
}
function notifi() {
modal.style.display = "block";
clr();
}
function explode() {
modal.style.display = "none";
}
setTimeout(explode, 3000);
function ref() {
location.reload();
}
function clr() {
document.getElementById("Location").value = "";
document.getElementById("pac-input").value = "";
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBPQ7PC_2JN_9jNw4z3N-PIsOtJF6HY-Hs&libraries=places&callback=initMap" async defer></script>
</body>
</html>
Related
Google Maps Traffic Widget
i want to show the widget from the picture above in my embedded map to show typical traffic. but i can't seem to find any documentation for this. this is my current javascript code
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 17,
clickableIcons: false,
center: {lat: 34.04924594193164, lng: -118.24104309082031}
});
var myMarker = new google.maps.Marker({
position: {lat: 34.04924594193164, lng: -118.24104309082031},
map: map,
title: 'myMarker',
draggable: false
});
var trafficLayer = new google.maps.TrafficLayer();
trafficLayer.setMap(map);
}
Exactly what you want is not provided in official document.
You can create custom legends base on this tutorial
function initMap() {
var options = {
zoom: 13,
center: {lat: 34.04924594193164, lng: -118.24104309082031},
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map-container'), options);
//var trafficLayer = new google.maps.TrafficLayer();
//trafficLayer.setMap(map);
var controlDiv = document.createElement('DIV');
$(controlDiv).addClass('gmap-control-container')
.addClass('gmnoprint');
var controlUI = document.createElement('DIV');
$(controlUI).addClass('gmap-control');
$(controlUI).text('Traffic');
$(controlDiv).append(controlUI);
var legend = '<ul>'
+ '<li><span style="background-color: #30ac3e"> </span><span style="color: #30ac3e"> > 80 km per hour</span></li>'
+ '<li><span style="background-color: #ffcf00"> </span><span style="color: #ffcf00"> 40 - 80 km per hour</span></li>'
+ '<li><span style="background-color: #ff0000"> </span><span style="color: #ff0000"> < 40 km per hour</span></li>'
+ '<li><span style="background-color: #c0c0c0"> </span><span style="color: #c0c0c0"> No data available</span></li>'
+ '</ul>';
var controlLegend = document.createElement('DIV');
$(controlLegend).addClass('gmap-control-legend');
$(controlLegend).html(legend);
$(controlLegend).hide();
$(controlDiv).append(controlLegend);
// Set hover toggle event
$(controlUI)
.mouseenter(function() {
$(controlLegend).show();
})
.mouseleave(function() {
$(controlLegend).hide();
});
var trafficLayer = new google.maps.TrafficLayer();
google.maps.event.addDomListener(controlUI, 'click', function() {
if (typeof trafficLayer.getMap() == 'undefined' || trafficLayer.getMap() === null) {
$(controlUI).addClass('gmap-control-active');
trafficLayer.setMap(map);
} else {
trafficLayer.setMap(null);
$(controlUI).removeClass('gmap-control-active');
}
});
map.controls[google.maps.ControlPosition.TOP_RIGHT].push(controlDiv);
}
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map-container {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
.gmap-control-container {
margin: 5px;
}
.gmap-control {
cursor: pointer;
background-color: -moz-linear-gradient(center top , #FEFEFE, #F3F3F3);
background-color: #FEFEFE;
border: 1px solid #A9BBDF;
border-radius: 2px;
padding: 0 6px;
line-height: 160%;
font-size: 12px;
font-family: Arial,sans-serif;
box-shadow: 2px 2px 3px rgba(0, 0, 0, 0.35);
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-o-user-select: none;
user-select: none;
}
.gmap-control:hover {
border: 1px solid #678AC7;
}
.gmap-control-active {
background-color: -moz-linear-gradient(center top , #6D8ACC, #7B98D9);
background-color: #6D8ACC;
color: #fff;
font-weight: bold;
border: 1px solid #678AC7;
}
.gmap-control-legend {
position: absolute;
text-align: left;
z-index: -1;
top: 20px;
right: 0;
width: 150px;
height: 66px;
font-size: 10px;
background: #FEFEFE;
border: 1px solid #A9BBDF;
padding: 10px;
box-shadow: 2px 2px 3px rgba(0, 0, 0, 0.35);
}
.gmap-control-legend ul {
margin: 0;
padding: 0;
list-style-type: none;
}
.gmap-control-legend li {
line-height: 160%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="map-container"></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>
I am trying to setup a page that has 2 different addresses and displays with maps using the google maps api from autocomplete. I have one working great but I cannot get 2 working on different divs? I would also like to post the data from both as variables as working on the first.
The html I have working for one but not the other is :
<div id="pickup-details">
<div class="col-md-10 col-md-offset-1 col-sm-10 col-sm-offset-1 col-xs-12">
<input id="searchInput" onfocus="this.value=''" class="controls" type="text" placeholder="Enter pickup address">
<div id="map"></div>
</div>
<div id="dropoff-details">
<div class="col-md-10 col-md-offset-1 col-sm-10 col-sm-offset-1 col-xs-12">
<input id="searchInput2" onfocus="this.value=''" class="controls2" type="text" placeholder="Enter dropoff address">
<div id="map2"></div>
</div>
The css is :
#map {width: 100%;height: 300px;}
.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);
}
#searchInput {
background-color: #fff;
font-size: 15px;
font-weight: 300;
margin-left: 12px;
padding: 0 11px 0 13px;
text-overflow: ellipsis;
width: 50%;
}
#searchInput:focus {
border-color: #4d90fe;
}
#map2 {width: 100%;height: 300px;}
.controls2 {
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);
}
#searchInput2 {
background-color: #fff;
font-size: 15px;
font-weight: 300;
margin-left: 12px;
padding: 0 11px 0 13px;
text-overflow: ellipsis;
width: 50%;
}
#searchInput2:focus {
border-color: #4d90fe;
}
and the js I have is :
var map;
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 52.48757519999999, lng: -1.9116437000000133},
zoom: 13
});
var map2 = new google.maps.Map(document.getElementById('map2'), {
center: {lat: 52.48757519999999, lng: -1.9116437000000133},
zoom: 13
});
var input = document.getElementById('searchInput');
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
var autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.bindTo('bounds', map);
var infowindow = new google.maps.InfoWindow();
var marker = new google.maps.Marker({
map: map,
anchorPoint: new google.maps.Point(0, -29)
});
autocomplete.addListener('place_changed', function() {
infowindow.close();
marker.setVisible(false);
var place = autocomplete.getPlace();
if (!place.geometry) {
window.alert("Autocomplete's returned place contains no geometry");
return;
}
// If the place has a geometry, then present it on a map.
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(17);
}
marker.setIcon(({
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(35, 35)
}));
marker.setPosition(place.geometry.location);
marker.setVisible(true);
var address = '';
if (place.address_components) {
address = [
(place.address_components[0] && place.address_components[0].short_name || ''),
(place.address_components[1] && place.address_components[1].short_name || ''),
(place.address_components[2] && place.address_components[2].short_name || ''),
(place.address_components[3] && place.address_components[3].short_name || ''),
(place.address_components[4] && place.address_components[4].short_name || ''),
(place.address_components[5] && place.address_components[5].short_name || ''),
(place.address_components[6] && place.address_components[6].short_name || '')
].join(' ');
}
infowindow.setContent('<div><strong>' + place.name + '</strong><br>' + address);
infowindow.open(map, marker);
//clear all//
document.getElementById('postal_code').value=null;
document.getElementById('administrative_area_level_1').value=null;
document.getElementById('locality').value=null;
document.getElementById('route').value=null;
document.getElementById('street_number').value=null;
document.getElementById('place_name').value=null;
//Location details
for (var i = 0; i < place.address_components.length; i++) {
if(place.address_components[i].types[0] == 'postal_code'){
document.getElementById('postal_code').value=place.address_components[i].short_name;
}
if(place.address_components[i].types[0] == 'country'){
document.getElementById('administrative_area_level_1').value=place.address_components[i].long_name;
}
if(place.address_components[i].types[0] == 'locality'){
document.getElementById('locality').value=place.address_components[i].long_name;
}
if(place.address_components[i].types[0] == 'route'){
var test2 = value=place.address_components[i].long_name;
document.getElementById('route').value=place.address_components[i].long_name;
}
if(place.address_components[i].types[0] == 'street_number'){
var test1 = value=place.address_components[i].long_name;
document.getElementById('street_number').value=place.address_components[i].long_name;
}
test3 = test1+' '+test2;
test4 = place.name;
if (test3 == test4) {
document.getElementById('place_name').value=null;
}
if (test3 != test4) {
document.getElementById('place_name').value=place.name;
}
}
document.getElementById('show_pick_up').innerHTML = place.name+' '+place.formatted_address;
$('#show_pick_up').show();
//document.getElementById('place_name').value=place.name;
//document.getElementById('route').value=place.address_components[1].short_name;
//document.getElementById('postal_code').value=place.address_components[6].short_name;
});
}
You have to create and initialize your 2 maps separately. You should store references to your 2 maps. This example is taken straight from Google Maps API examples: Simple Map You will see 2 maps starting at 2 different locations.
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644},
zoom: 8
});
map2 = new google.maps.Map(document.getElementById('map2'), {
center: {lat: 42.2007934, lng: -85.604063},
zoom: 8
});
}
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 250px;
width: 250px;
float: left;
}
#map2 {
height: 250px;
width: 250px;
float: right;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
<div id="map"></div>
<div id="map2"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script src="https://maps.googleapis.com/maps/api/js?callback=initMap" async defer></script>
The problem is sorted with the map not loading automatically, I just had to add the below when the div was reloaded
window.dispatchEvent(new Event('resize'));
I'm trying to get the location inside the text field automatically when ever I write some location! but it's not working and no location is showing up when I write something. please help me to resolve it. Thanks in advance. I am trying to get values in next page. and it is working perfectly just want the intelicence of google map address.
Here is the code:
<!DOCTYPE html>
<html>
<head>
<title>Place Autocomplete</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<script>
function sync()
{
var n1 = document.getElementById('n1');
var n2 = document.getElementById('pac-input');
n1.value = n2.value;
}
</script>
<style>
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;
}
</style>
</head>
<body>
<div id="type-selector" class="controls">
<form name='form' method="get" action="Input.php">
<input type="hidden" id="n1" name="name1">
<input id="pac-input" name="name" class="controls" type="text"
placeholder="Enter a location" onmouseout="sync()">
<input type="radio" name="type" id="changetype-all" checked="checked">
<label for="changetype-all">All</label>
<input type="radio" name="type" id="changetype-establishment">
<label for="changetype-establishment">Establishments</label>
<input type="radio" name="type" id="changetype-address">
<label for="changetype-address">Addresses</label>
<input type="radio" name="type" id="changetype-geocode">
<label for="changetype-geocode">Geocodes</label>
<input type="submit" name="submit" value="Submit" >
</form>
</div>
<div id="map"></div>
<script>
// 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 map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -33.8688, lng: 151.2195},
zoom: 13
});
var input = /** #type {!HTMLInputElement} */(
document.getElementById('pac-input'));
var types = document.getElementById('type-selector');
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
map.controls[google.maps.ControlPosition.TOP_LEFT].push(types);
var autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.bindTo('bounds', map);
var infowindow = new google.maps.InfoWindow();
var marker = new google.maps.Marker({
map: map,
anchorPoint: new google.maps.Point(0, -29)
});
autocomplete.addListener('place_changed', function() {
infowindow.close();
marker.setVisible(false);
var place = autocomplete.getPlace();
if (!place.geometry) {
window.alert("Autocomplete's returned place contains no geometry");
return;
}
// If the place has a geometry, then present it on a map.
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(17); // Why 17? Because it looks good.
}
marker.setIcon(/** #type {google.maps.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(35, 35)
}));
marker.setPosition(place.geometry.location);
marker.setVisible(true);
var address = '';
if (place.address_components) {
address = [
(place.address_components[0] && place.address_components[0].short_name || ''),
(place.address_components[1] && place.address_components[1].short_name || ''),
(place.address_components[2] && place.address_components[2].short_name || '')
].join(' ');
}
infowindow.setContent('<div><strong>' + place.name + '</strong><br>' + address);
infowindow.open(map, marker);
});
// Sets a listener on a radio button to change the filter type on Places
// Autocomplete.
function setupClickListener(id, types) {
var radioButton = document.getElementById(id);
radioButton.addEventListener('click', function() {
autocomplete.setTypes(types);
});
}
setupClickListener('changetype-all', []);
setupClickListener('changetype-address', ['address']);
setupClickListener('changetype-establishment', ['establishment']);
setupClickListener('changetype-geocode', ['geocode']);
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDMphVv_7FuU0Yi1ofpDNnO1r9wppukLxo&libraries&libraries=places&callback=initMap"
async defer></script>
</body>
</html>
As the title says, I am trying to use a location suggestion by using google API autocomplete without creating a google map. I've found some code on multiple sites and tried to put it together, filling in the missing parts, but so far it hasn't work. I was wondering if anyone knows how google API works and could help me out, thanks!
HTML:
<head>
....
<script src="file.js"></script>
....
</head>
<body>
....
<input type="text" class="form-control" id="university" onfocus="geolocate()" placeholder="Name of University" required>
....
<script src="https://maps.googleapis.com/maps/api/js?key=API_KEY&signed_in=true&libraries=places&callback=initialize" async defer></script>
</body>
JS:
/*global google */
var autocomplete;
function initialize() {
"use strict";
autocomplete = new google.maps.places.Autocomplete(document.getElementById("university"), {types: ["geocode"]});
}
function geolocate() {
"use strict";
var geolocation, circle;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
geolocation = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
circle = new google.maps.Circle({
center: geolocation,
radius: position.coords.accuracy
});
autocomplete.setBounds(circle.getBounds());
});
}
}
Below is provided a Place Autocomplete example without any dependency to google.maps.Map class:
function initMap() {
var input = document.getElementById('pac-input');
var autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.addListener('place_changed', function() {
var place = autocomplete.getPlace();
if (!place.geometry) {
window.alert("Autocomplete's returned place contains no geometry");
return;
}
var address = '';
if (place.address_components) {
address = [
(place.address_components[0] && place.address_components[0].short_name || ''),
(place.address_components[1] && place.address_components[1].short_name || ''),
(place.address_components[2] && place.address_components[2].short_name || '')
].join(' ');
}
document.getElementById('placeInfo').innerHTML = '<div><strong>' + place.name + '</strong><br>' + address;
});
}
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;
}
<input id="pac-input" class="controls" type="text"
placeholder="Enter a location"/>
<pre id="placeInfo"></pre>
<script src="https://maps.googleapis.com/maps/api/js?libraries=places&callback=initMap"
async defer></script>
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"