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();
}
}
}
}
Related
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 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 want to use the Google Places API linked to an input so a user can enter in a street address and I can get the geo location.
From there, I want to be able to adjust this map to have the input location in the centre.
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.
var marker = new google.maps.Marker({
map: map,
});
marker.bindTo('position', map, 'center');
searchBox.addListener('places_changed', function() {
var places = searchBox.getPlaces();
if (places.length == 0) {
return;
}
// Clear out the old markers.
markers.forEach(function(mark) {
mark.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 icon = {
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(25, 25)
};
// Create a marker for each place.
markers.push(new google.maps.Marker({
map: map,
icon: icon,
title: place.name,
position: place.geometry.location
}));
if (place.geometry.viewport) {
// Only geocodes have viewport.
bounds.union(place.geometry.viewport);
} else {
bounds.extend(place.geometry.location);
}
});
map.fitBounds(bounds);
});
}
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
}
.controls {
margin-top: 10px;
border: 1px solid transparent;
border-radius: 2px 0 0 2px;
box-sizing: border-box;
-moz-box-sizing: border-box;
height: 32px;
outline: none;
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
}
#pac-input {
background-color: #fff;
font-family: Roboto;
font-size: 15px;
font-weight: 300;
margin-left: 12px;
padding: 0 11px 0 13px;
text-overflow: ellipsis;
width: 300px;
}
#pac-input:focus {
border-color: #4d90fe;
}
.pac-container {
font-family: Roboto;
}
#type-selector {
color: #fff;
background-color: #4d90fe;
padding: 5px 11px 0px 11px;
}
#type-selector label {
font-family: Roboto;
font-size: 13px;
font-weight: 300;
}
#target {
width: 345px;
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=places&key=YOUR_API_KEY"></script>
<input id="pac-input" class="controls" type="text" placeholder="Search Box">
<div id="map"></div>
Snippet has been updated.
i am totally new in Javascript. I have a project to make a program (based on web page) connected to google maps.
i have read developer.google.com and stuck with it.
Please help me, how to joining two sample codes place search box (https://developers.google.com/maps/documentation/javascript/examples/places-searchbox) and marker remove (https://developers.google.com/maps/documentation/javascript/examples/marker-remove)
thanks
Update: this is my code (for now)
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Places Searchbox</title>
<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;
}
#target {
width: 345px;
}
#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>
</head>
<body>
<input id="pac-input" class="controls" type="text" placeholder="Search Box">
<div id="floating-panel">
<input onclick="clearMarkers();" type=button value="Hide Markerr">
<input onclick="showMarkers();" type=button value="Show All Markerr">
<input onclick="deleteMarkers();" type=button value="Delete Markerr">
</div>
<div id="map"></div>
<script>
// This example adds a search box to a map, using the Google Place Autocomplete
// feature. People can enter geographical searches. The search box will return a
// pick list containing a mix of places and predicted search terms.
// This example requires the Places library. Include the libraries=places
// parameter when you first load the API. For example:
// <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places">
function initAutocomplete() {
var Markerr = [];
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -7.266813, lng: 112.770218},
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 icon = {
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(25, 25)
};
// Create a marker for each place.
markers.push(new google.maps.Marker({
map: map,
icon: icon,
title: place.name,
position: place.geometry.location
}));
if (place.geometry.viewport) {
// Only geocodes have viewport.
bounds.union(place.geometry.viewport);
} else {
bounds.extend(place.geometry.location);
}
});
map.fitBounds(bounds);
});
// -----------------------------
// This event listener will call addMarker() when the map is clicked.
map.addListener('click', function(event) {
addMarker(event.latLng);
});
// Adds a marker at the center of the map.
addMarker(haightAshbury);
// *********************************
}
// Adds a marker to the map and push to the array.
function addMarker(location) {
var marker = new google.maps.Marker({
position: location,
map: map
});
Markerr.push(marker);
}
// Sets the map on all Markerr in the array.
function setMapOnAll(map) {
for (var i = 0; i < Markerr.length; i++) {
Markerr[i].setMap(map);
}
}
// Removes the Markerr from the map, but keeps them in the array.
function clearMarkers() {
setMapOnAll(null);
}
// Shows any Markerr currently in the array.
function showMarkers() {
setMapOnAll(map);
}
// Deletes all Markerr in the array by removing references to them.
function deleteMarkers() {
clearMarkers();
Markerr = [];
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=[API]&libraries=places&callback=initAutocomplete"
async defer></script>
</body>
</html>
You have errors in the posted javascript.
Uncaught ReferenceError: haightAshbury is not defined
Uncaught ReferenceError: Markerr is not defined
...
The main problem is that the markers array and the map variable are not in the global scope, once those are moved to the global scope and the references to the Markerr array removed (or changed to markers), the buttons work (or at least do what I expect).
proof of concept fiddle
code snippet:
// global variables
var markers = [];
var map;
function initAutocomplete() {
// initialize the global map variable
map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: -7.266813,
lng: 112.770218
},
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);
var floatBox = document.getElementById('floating-panel'); map.controls[google.maps.ControlPosition.TOP_LEFT].push(floatBox);
// Bias the SearchBox results towards current map's viewport.
map.addListener('bounds_changed', function() {
searchBox.setBounds(map.getBounds());
});
// Listen for the event fired when the user selects a prediction and retrieve
// more details for that place.
searchBox.addListener('places_changed', function() {
var places = searchBox.getPlaces();
if (places.length == 0) {
return;
}
// Clear out the old markers.
markers.forEach(function(marker) {
marker.setMap(null);
});
markers = [];
// For each place, get the icon, name and location.
var bounds = new google.maps.LatLngBounds();
places.forEach(function(place) {
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.
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);
});
// -----------------------------
// This event listener will call addMarker() when the map is clicked.
map.addListener('click', function(event) {
addMarker(event.latLng);
});
// Adds a marker at the center of the map.
// addMarker(haightAshbury);
// *********************************
}
// Adds a marker to the map and push to the array.
function addMarker(location) {
var marker = new google.maps.Marker({
position: location,
map: map
});
markers.push(marker);
}
// Sets the map on all Markerr in the array.
function setMapOnAll(map) {
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(map);
}
}
// Removes the Markerr from the map, but keeps them in the array.
function clearMarkers() {
setMapOnAll(null);
}
// Shows any Markerr currently in the array.
function showMarkers() {
setMapOnAll(map);
}
// Deletes all Markerr in the array by removing references to them.
function deleteMarkers() {
clearMarkers();
markers = [];
}
google.maps.event.addDomListener(window, "load", initAutocomplete);
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
}
.controls {
margin-top: 10px;
border: 1px solid transparent;
border-radius: 2px 0 0 2px;
box-sizing: border-box;
-moz-box-sizing: border-box;
height: 32px;
outline: none;
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
}
#pac-input {
background-color: #fff;
font-family: Roboto;
font-size: 15px;
font-weight: 300;
margin-left: 12px;
padding: 0 11px 0 13px;
text-overflow: ellipsis;
width: 300px;
}
#pac-input:focus {
border-color: #4d90fe;
}
.pac-container {
font-family: Roboto;
}
#type-selector {
color: #fff;
background-color: #4d90fe;
padding: 5px 11px 0px 11px;
}
#type-selector label {
font-family: Roboto;
font-size: 13px;
font-weight: 300;
}
#target {
width: 345px;
}
#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;
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=places"></script>
<div id="floating-panel">
<input id="pac-input" class="controls" type="text" placeholder="Search Box" /><br>
<input onclick="clearMarkers();" type=button value="Hide Markerr">
<input onclick="showMarkers();" type=button value="Show All Markerr">
<input onclick="deleteMarkers();" type=button value="Delete Markerr">
</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"