How can i make it follow my exact location using geolocation? - javascript

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"

Related

Info window with place details is not showing (Google Places API)

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>

Google maps marker custom context menu

I am trying to create a custom context menu for google maps that will only work if I click a marker but this context menu that I am using will display the context menu anywhere I click. I want to make the context menu specifically for the map marker.
HTML:
<div id="map" style="width:100%;height:500px"></div>
<div class="menu" id="menu">
<div class="menu-item"><i class="glyphicon glyphicon-file"></i>Manage files</div>
</div>
JS:
function myMap() {
var menuDisplayed = false;
var menuBox = null;
var myCenter = new google.maps.LatLng(51.508742,-0.120850);
var mapCanvas = document.getElementById("map");
var mapOptions = {center: myCenter, zoom: 5};
var map = new google.maps.Map(mapCanvas, mapOptions);
var marker = new google.maps.Marker({position:myCenter});
marker.setMap(map);
window.addEventListener("contextmenu", function() {
var left = arguments[0].clientX;
var top = arguments[0].clientY;
menuBox = document.getElementById("menu");
menuBox.style.left = left + "px";
menuBox.style.top = top + "px";
menuBox.style.display = "block";
arguments[0].preventDefault();
menuDisplayed = true;
}, false);
window.addEventListener("click", function() {
if(menuDisplayed == true){
menuBox.style.display = "none";
}
}, true);
}
CSS:
.menu {
width: 150px;
box-shadow: 3px 3px 5px #888888;
border-style: solid;
border-width: 1px;
border-color: grey;
border-radius: 2px;
position: fixed;
display: none;
}
.menu-item {
height: 20px;
background-color: white;
}
.menu-item:hover {
background-color: #6CB5FF;
cursor: pointer;
}
One option would be rather than capturing all the clicks on the window object, just capture rightclick on the marker, open your context menu, close it on clicks on the map.
marker.addListener("rightclick", function(e) {
for (prop in e) {
if (e[prop] instanceof MouseEvent) {
mouseEvt = e[prop];
var left = mouseEvt.clientX;
var top = mouseEvt.clientY;
menuBox = document.getElementById("menu");
menuBox.style.left = left + "px";
menuBox.style.top = top + "px";
menuBox.style.display = "block";
mouseEvt.preventDefault();
menuDisplayed = true;
}
}
});
map.addListener("click", function(e) {
if (menuDisplayed == true) {
menuBox.style.display = "none";
}
});
proof of concept fiddle
code snippet:
function myMap() {
var menuDisplayed = false;
var menuBox = null;
var myCenter = new google.maps.LatLng(51.508742, -0.120850);
var mapCanvas = document.getElementById("map");
var mapOptions = {
center: myCenter,
zoom: 5
};
var map = new google.maps.Map(mapCanvas, mapOptions);
var marker = new google.maps.Marker({
position: myCenter
});
marker.setMap(map);
marker.addListener("rightclick", function(e) {
for (prop in e) {
if (e[prop] instanceof MouseEvent) {
mouseEvt = e[prop];
var left = mouseEvt.clientX;
var top = mouseEvt.clientY;
menuBox = document.getElementById("menu");
menuBox.style.left = left + "px";
menuBox.style.top = top + "px";
menuBox.style.display = "block";
mouseEvt.preventDefault();
menuDisplayed = true;
}
}
});
map.addListener("click", function(e) {
if (menuDisplayed == true) {
menuBox.style.display = "none";
}
});
}
google.maps.event.addDomListener(window, "load", myMap);
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
.menu {
width: 150px;
box-shadow: 3px 3px 5px #888888;
border-style: solid;
border-width: 1px;
border-color: grey;
border-radius: 2px;
position: fixed;
display: none;
}
.menu-item {
height: 20px;
background-color: white;
}
.menu-item:hover {
background-color: #6CB5FF;
cursor: pointer;
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map"></div>
<div class="menu" id="menu">
<div class="menu-item"><i class="glyphicon glyphicon-file"></i>Manage files</div>
</div>

google map appear with grey inside modal in bootstrap

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>

google places api autocomplete - adding click event

I'm appending a Search Results to the google places javascript api autocomplete.
So far I'm doing this:
var autocomplete;
function initialize() {
var myLatlng = new google.maps.LatLng(40.738793, -73.991402);
autocomplete = new google.maps.places.Autocomplete(document.getElementById('autocomplete'));
}
later on I have this:
$('.pac-container').append( '<div class="j-search pac-item-refresh">Search Results</div>' );
$(document.body).on('click', '.pac-container .j-search', function(e) {
console.log('click fired');
});
The problem? The click event never fires...
Any idea why? Anything wrong with my code?
It seems that the click-event for .pac-container is cancelled by the Autocomplete-instance. Use mousedown instead.
You can follow the this article.
Implement and Optimize Autocomplete with Google Places API
Specifically Autocompletion using the AutocompleteService:
link: JS Filddle Of AutocompletionService
function debounce(func, wait, immediate) {
let timeout;
return function() {
let context = this,
args = arguments;
let later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
let callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
}
function initAutocomplete() {
let map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: 48,
lng: 4
},
zoom: 4,
disableDefaultUI: true
});
// Create the search box and link it to the UI element.
let inputContainer = document.querySelector('autocomplete-input-container');
let autocomplete_results = document.querySelector('.autocomplete-results');
let service = new google.maps.places.AutocompleteService();
let serviceDetails = new google.maps.places.PlacesService(map);
let marker = new google.maps.Marker({
map: map
});
let displaySuggestions = function(predictions, status) {
if (status != google.maps.places.PlacesServiceStatus.OK) {
alert(status);
return;
}
let results_html = [];
predictions.forEach(function(prediction) {
results_html.push(`<li class="autocomplete-item" data-type="place" data-place-id=${prediction.place_id}><span class="autocomplete-icon icon-localities"></span> <span class="autocomplete-text">${prediction.description}</span></li>`);
});
autocomplete_results.innerHTML = results_html.join("");
autocomplete_results.style.display = 'block';
let autocomplete_items = autocomplete_results.querySelectorAll('.autocomplete-item');
for (let autocomplete_item of autocomplete_items) {
autocomplete_item.addEventListener('click', function() {
let prediction = {};
const selected_text = this.querySelector('.autocomplete-text').textContent;
const place_id = this.getAttribute('data-place-id');
let request = {
placeId: place_id,
fields: ['name', 'geometry']
};
serviceDetails.getDetails(request, function(place, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
if (!place.geometry) {
console.log("Returned place contains no geometry");
return;
}
var bounds = new google.maps.LatLngBounds();
marker.setPosition(place.geometry.location);
if (place.geometry.viewport) {
bounds.union(place.geometry.viewport);
} else {
bounds.extend(place.geometry.location);
}
map.fitBounds(bounds);
}
autocomplete_input.value = selected_text;
autocomplete_results.style.display = 'none';
});
})
}
};
let autocomplete_input = document.getElementById('my-input-autocomplete');
autocomplete_input.addEventListener('input', debounce(function() {
let value = this.value;
value.replace('"', '\\"').replace(/^\s+|\s+$/g, '');
if (value !== "") {
service.getPlacePredictions({
input: value
}, displaySuggestions);
} else {
autocomplete_results.innerHTML = '';
autocomplete_results.style.display = 'none';
}
}, 150));
}
document.addEventListener("DOMContentLoaded", function(event) {
initAutocomplete();
});
#map {
height: 100%;
}
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
.autocomplete-input-container {
position: absolute;
z-index: 1;
width: 100%;
}
.autocomplete-input {
text-align: center;
}
#my-input-autocomplete {
box-shadow: 0 2px 2px 0 rgba(0, 0, 0, 0.16), 0 0 0 1px rgba(0, 0, 0, 0.08);
font-size: 15px;
border-radius: 3px;
border: 0;
margin-top: 10px;
width: 290px;
height: 40px;
text-overflow: ellipsis;
padding: 0 1em;
}
#my-input-autocomplete:focus {
outline: none;
}
.autocomplete-results {
margin: 0 auto;
right: 0;
left: 0;
position: absolute;
display: none;
background-color: white;
width: 320px;
padding: 0;
list-style-type: none;
margin: 0 auto;
border: 1px solid #d2d2d2;
border-top: 0;
box-sizing: border-box;
}
.autocomplete-item {
padding: 5px 5px 5px 35px;
height: 26px;
line-height: 26px;
border-top: 1px solid #d9d9d9;
position: relative;
white-space: nowrap;
text-overflow: ellipsis;
overflow: hidden;
}
.autocomplete-icon {
display: block;
position: absolute;
top: 7px;
bottom: 0;
left: 8px;
width: 20px;
height: 20px;
background-repeat: no-repeat;
background-position: center center;
}
.autocomplete-icon.icon-localities {
background-image: url(https://images.woosmap.com/icons/locality.svg);
}
.autocomplete-item:hover .autocomplete-icon.icon-localities {
background-image: url(https://images.woosmap.com/icons/locality-selected.svg);
}
.autocomplete-item:hover {
background-color: #f2f2f2;
cursor: pointer;
}
.autocomplete-results::after {
content: "";
padding: 1px 1px 1px 0;
height: 18px;
box-sizing: border-box;
text-align: right;
display: block;
background-image: url(https://maps.gstatic.com/mapfiles/api-3/images/powered-by-google-on-white3_hdpi.png);
background-position: right;
background-repeat: no-repeat;
background-size: 120px 14px
}
<div class="autocomplete-input-container">
<div class="autocomplete-input">
<input id="my-input-autocomplete" placeholder="AutocompleteService" autocomplete="off" role="combobox">
</div>
<ul class="autocomplete-results">
</ul>
</div>
<div id="map"></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"></script>

dynamic infowindow with dynamic markers

I am writing because I have made ​​a script that takes the json data to create multiple dynamic marker, and it works!
Now I'm trying to add the InfoWindow to each marker, but does not work.
My code is:
$.ajax({
type:'GET',
url:"locali_json.php"+urlz,
success:function(data){
var json = JSON.parse(data);
for (var i=0; i<json.length; i++) {
point = new google.maps.LatLng(json[i].latitudine,json[i].longitudine);
contentString = json[i].id_locale;
addMarkers(point,contentString);
}
}
})}
function addMarkers(point,contentString) {
marker = new google.maps.Marker({
position: point,
map: map
});
infowindow = new google.maps.InfoWindow({
content: contentString
});
markers.push(marker); // markers is an array
infos.push(infowindow); //info is an array
for(var j=0; j<markers.lenght; j++){
google.maps.event.addListener(marker, 'click', function() {
infos[j].open(map,markers[j]);})
}}
anyone have any suggestions? or see where error?
Don't you get javascript errors in the javascript console?
for(var j=0; j<markers.lenght; j++){
google.maps.event.addListener(marker, 'click', function() {
infos[j].open(map,markers[j]);})
}
}
Should probably be:
for(var j=0; j<markers.length; j++){
google.maps.event.addListener(markers[j], 'click', function() {
infos[j].open(map,markers[j]);})
}
}
I did it this way, you can try it. Includes a customized info window.
Index.cshtml
#{
Layout = null;
}
<html>
<head>
<style>
#map-canvas {
margin: 0;
padding: 0;
height: 400px;
max-width: none;
}
.gm-style-iw {
width: 350px !important;
/*top: 0px !important;
left: 0px !important;
background-color: #fff;
box-shadow: 0 1px 6px rgba(178, 178, 178, 0.6);
border: 1px solid rgba(72, 181, 233, 0.6);
border-radius: 10px 10px 10px 10px;*/
}
#iw-container {
margin-bottom: 10px;
}
#iw-container .iw-title {
font-family: 'Open Sans Condensed', sans-serif;
font-size: 22px;
font-weight: 400;
padding: 20px;
background-color: #39ac73;
color: white;
margin: 2px;
border-radius: 2px 2px 0 0;
}
#iw-container .iw-content {
font-size: 13px;
line-height: 18px;
font-weight: 400;
margin-right: 1px;
padding: 15px 5px 20px 15px;
max-height: 200px;
overflow-y: auto;
overflow-x: hidden;
}
#map-canvas img {
max-width: none !important;
}
.iw-subTitle {
font-size: 16px;
font-weight: 700;
padding: 5px 0;
}
.infoDiv {
height: 200px;
width: 300px;
-webkit-user-select: none;
background-color: white;
}
.iw-bottom-gradient {
position: absolute;
width: 326px;
height: 25px;
bottom: 10px;
right: 18px;
background: linear-gradient(to bottom, rgba(255,255,255,0) 0%, rgba(255,255,255,1) 100%);
background: -webkit-linear-gradient(top, rgba(255,255,255,0) 0%, rgba(255,255,255,1) 100%);
background: -moz-linear-gradient(top, rgba(255,255,255,0) 0%, rgba(255,255,255,1) 100%);
background: -ms-linear-gradient(top, rgba(255,255,255,0) 0%, rgba(255,255,255,1) 100%);
}
</style>
</head>
<body>
<div id="map-canvas" style="width: 1800px; height: 1500px">
</div>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=APIKEY"></script>
<script type="text/javascript">
var markers = #Html.Raw(ViewBag.Markers);
window.onload = function () {
var mapOptions = {
center: new google.maps.LatLng(markers[0].lat, markers[0].lng),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var infoWindow = new google.maps.InfoWindow();
var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
for (i = 0; i < markers.length; i++) {
var data = markers[i]
var myLatlng = new google.maps.LatLng(data.lat, data.lng);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: data.title,
description: data.description,
icon: "http://maps.google.com/mapfiles/ms/icons/green-dot.png",
animation: google.maps.Animation.DROP,
});
// Add the circle for this city to the map.
var cityCircle = new google.maps.Circle({
strokeColor: '#FFFFFF',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FFFFFF',
fillOpacity: 0.35,
map: map,
center: myLatlng,
radius: 19999.45454,
position: myLatlng,
draggable: false
});
(function (marker, data) {
google.maps.event.addListener(marker, "click", function (e) {
infoWindow.setContent('<div id="iw-container">' +
'<div class="iw-title">' + data.title + "</div>" + '<div class="iw-content">'
+ "<p>" + data.description + "</p>"+'<img src="http://maps.marnoto.com/en/5wayscustomizeinfowindow/images/vistalegre.jpg" alt="Porcelain Factory of Vista Alegre" height="115" width="83">'
+'<div class="iw-bottom-gradient"></div>');
//infoWindow.setContent(data.title);
//infoWindow.setContent(data.description);
infoWindow.open(map, marker);
});
})(marker, data);
}
}
</script>
</body>
</html>
Controller:
namespace Map.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
{
string markers = "[";
string conString = ConfigurationManager.ConnectionStrings["PTS"].ConnectionString;
SqlCommand cmd = new SqlCommand("SELECT * FROM ProjeIlani");
using (SqlConnection con = new SqlConnection(conString))
{
cmd.Connection = con;
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
markers += "{";
markers += string.Format("'title': '{0}',", sdr["Adres"]);
markers += string.Format("'lat': '{0}',", sdr["Enlem"]);
markers += string.Format("'lng': '{0}',", sdr["Boylam"]);
markers += string.Format("'description': '{0}'", sdr["Aciklama"]);
markers += "},";
}
}
con.Close();
}
markers += "];";
ViewBag.Markers = markers;
return View();
}
}
}
}

Categories