Google Maps Hiding Marker Labels - javascript

Is there a way to hide marker labels after I created them?
I researched and found MarkerWithLabel, but I don't want to use 3rd libraries.
Creating labels inside the markers like that
new google.maps.Marker({ label:{text:'test',color:'black'} });
I want to hide and show them with a checkbox.

Related question: Google map marker label text color change
To hide the label, call marker.setLabel("");
To restore it, save the original value in another property of the marker (say _label), and use that to set the value when the checkbox value changes:
google.maps.event.addDomListener(document.getElementById('chkbx'), 'click', function() {
var checked = document.getElementById('chkbx').checked;
if (!checked) {
// remove the labels
for (var i=0; i<markers.length; i++)
markers[i].setLabel("");
} else {
for (var i=0; i<markers.length; i++)
markers[i].setLabel(markers[i]._label);
}
});
proof of concept fiddle
code snippet:
var geocoder;
var map;
var markers = [];
function initialize() {
map = new google.maps.Map(
document.getElementById("map_canvas"), {
center: new google.maps.LatLng(37.4419, -122.1419),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
// Mountain View, CA, USA (37.3860517, -122.0838511)
var marker1 = createMarker({
lat: 37.3860517,
lng: -122.0838511
}, "Mountain View, CA", "A");
// Palo Alto, CA, USA (37.4418834, -122.14301949999998)
var marker2 = createMarker({
lat: 37.4418834,
lng: -122.14301949999998
}, "Palo Alto", "B");
// Stanford, CA, USA (37.42410599999999, -122.1660756)
var marker3 = createMarker({
lat: 37.42410599999999,
lng: -122.1660756
}, "Stanford, CA", "C");
var bounds = new google.maps.LatLngBounds();
bounds.extend(marker1.getPosition());
bounds.extend(marker2.getPosition());
bounds.extend(marker3.getPosition());
map.fitBounds(bounds);
google.maps.event.addDomListener(document.getElementById('chkbx'), 'click', function() {
var checked = document.getElementById('chkbx').checked;
if (!checked) {
// remove the labels
for (var i = 0; i < markers.length; i++)
markers[i].setLabel("");
} else {
for (var i = 0; i < markers.length; i++)
markers[i].setLabel(markers[i]._label);
}
});
}
google.maps.event.addDomListener(window, "load", initialize);
function createMarker(latLng, text, label) {
var marker = new google.maps.Marker({
position: latLng,
map: map,
label: {
text: label,
color: "white"
},
_label: {
text: label,
color: "white"
}
});
markers.push(marker);
return marker;
}
html,
body {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px;
}
#map_canvas {
height: 90%;
width: 100%;
}
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<input type="checkbox" id="chkbx" name="chkbx" checked="checked" />toggle marker labels
<div id="map_canvas"></div>

Related

Tag place types in google map street-view api

I'm new to Google Maps API and using streetview.
I want to display the tag in each place in streetview the once I screenshot.
(see there is orange and blue tag eg. restaurant, cafe, clothing store)
as per Mr. Upsidedown, added working API key which is free for use on Stack overflow.
I was able to pin some places type using the Places API and it pin on maps but did not pin on streetview.
var map;
function createMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: { lat: 42.345573, lng: -71.098326 },
zoom: 20
});
var request = {
location: map.getCenter(),
radius: 8047,
types: ['cafe']
}
var service = new google.maps.places.PlacesService(map);
service.nearbySearch(request, callback);
const panorama = new google.maps.StreetViewPanorama(
document.getElementById("pano"),
{
position: map.getCenter(),
pov: {
heading: 34,
pitch: 10,
},
}
);
map.setStreetView(panorama);
}
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
console.log(results.length);
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
}
}
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location,
title: place.name
})
}
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
#map,
#pano {
float: left;
height: 100%;
width: 50%;
}
<div id="map"></div>
<div id="pano"></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=createMap" async defer></script>
If you need the markers to be visible on both the map and on Street View, just create the markers on map and panorama.
See my comments in the code. I also modified the center point and pano heading so that a Marker is in view when loaded.
var map;
var panorama; // Added this so that panorama is in global scope
function createMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: { lat: 42.344268, lng: -71.101617 },
zoom: 20
});
var request = {
location: map.getCenter(),
radius: 8047,
types: ['cafe']
}
var service = new google.maps.places.PlacesService(map);
service.nearbySearch(request, callback);
panorama = new google.maps.StreetViewPanorama(
document.getElementById("pano"),
{
position: map.getCenter(),
pov: {
heading: 65,
pitch: 10,
},
}
);
map.setStreetView(panorama);
}
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
console.log(results.length);
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
}
}
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location,
title: place.name
});
// added this to also add the Marker on panorama
var marker_pano = new google.maps.Marker({
map: panorama,
position: place.geometry.location,
title: place.name
});
}
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
#map,
#pano {
float: left;
height: 100%;
width: 50%;
}
<div id="map"></div>
<div id="pano"></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=createMap" async defer></script>

How to open web links from some Google Maps markers?

I can open web link from marker by
google.maps.event.addListener(marker, "click", function() {
window.open('http://example.com/');
});
But what if I need to place 100 markers with 100 links to Google Maps?
My array with coordinates and links looks like this
var point = [[52.7081444444445, 58.6677361111111, "Sib/2377/index.html"],
[52.7039611111111, 58.668425, "Sib/2378/index.html"],
[52.6993166666667, 58.6680305555556, "Sib/2379/index.html"],
[52.6946277777778, 58.6679416666667, "Sib/2380/index.html"],
[52.6947833333333, 58.6755555555556, "Sib/2381/index.html"]];
add the URL as a property of the marker (.url). Open the window using this.url
for (var i = 0; i < points.length; i++) {
var point = points[i];
var marker = new google.maps.Marker({
position: {
lat: point[0],
lng: point[1]
},
map: map,
url: point[2]
});
google.maps.event.addListener(marker, "click", function() {
window.open(this.url);
});
}
proof of concept fiddle
code snippet:
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: {
lat: -33.9,
lng: 151.2
}
});
setMarkers(map);
}
// Data for the markers consisting of a Latitude, a Longitude and a URL.
var points = [
[52.7081444444445, 58.6677361111111, "http://www.google.com"],
[52.7039611111111, 58.668425, "http://www.yahoo.com"],
[52.6993166666667, 58.6680305555556, "http://maps.google.com"],
[52.6946277777778, 58.6679416666667, "http://maps.google.com?q=52.6946277777778,58.6679416666667"],
[52.6947833333333, 58.6755555555556, "http://maps.google.com?q=52.6947833333333,58.6755555555556"]
];
function setMarkers(map) {
var bounds = new google.maps.LatLngBounds();
// Adds markers to the map.
for (var i = 0; i < points.length; i++) {
var point = points[i];
var marker = new google.maps.Marker({
position: {
lat: point[0],
lng: point[1]
},
map: map,
url: point[2]
});
google.maps.event.addListener(marker, "click", function() {
window.open(this.url);
});
bounds.extend(marker.getPosition());
}
map.fitBounds(bounds);
}
html,
body,
#map {
height: 100%;
margin: 0;
padding: 0;
}
<div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap">
</script>

Recenter map with multiple markers

I display multiple markers on a map. The list of locations is built with PHP:
$myData .= '["'.$Name.'", '.$lat.', '.$blon.'],';
Then I use JS to plot markers on the map.
function initMap() {
var map = new google.maps.Map(document.getElementById("map"), {
zoom: 12,
center: {lat: 32.99999999, lng: -95.2222328}
});
setMarkers(map);
}
var stores = ['.$myData.'];
function setMarkers(map) {
for (var i = 0; i < stores.length; i++) {
var store = stores[i];
var marker = new google.maps.Marker({
position: {lat: store[1], lng: store[2]},
map: map,
title: restaurant[0]
});
}
}
I need to re-center the map on map load. Should I try to average lat/lon coords from $myData array and replace center coords in initMap or is there a better way?
In this story: It's better to get average lat/long coordinates from the back-end (or calculate it on a front-end, but before you initialize a GoogleMap), so your map will be loaded in the right place and will not "tremble".
But you still may have a problem with zooming, and there are a few solutions. Most difficult is calculate again, but maybe you can try something of it (and it may make an interesting effect on page loading):
A. Zoom in from the space. Set smallest zoom and after google.API calculates bounding box — zoom in!
B. Show preloader screen over the map. In this case, you can calculate average lat/long using google.API too. It's the easiest way, but not so smooth and cool.
create an empty bounds object (a google.maps.LatLngBounds)
add all your markers to it
use it to center and zoom your map
function setMarkers(map) {
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < stores.length; i++) {
var store = stores[i];
var marker = new google.maps.Marker({
position: {lat: store[1], lng: store[2]},
map: map,
title: restaurant[0]
});
bounds.extend(marker.getPosition());
}
map.fitBounds(bounds);
}
code snippet:
function initMap() {
var map = new google.maps.Map(document.getElementById("map"), {
zoom: 12,
center: {
lat: 32.99999999,
lng: -95.2222328
}
});
setMarkers(map);
}
var stores = [
["store 1", 42, -72],
["store 2", 41, -74]
];
function setMarkers(map) {
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < stores.length; i++) {
var store = stores[i];
var marker = new google.maps.Marker({
position: {
lat: store[1],
lng: store[2]
},
map: map,
title: store[0]
});
bounds.extend(marker.getPosition());
}
map.fitBounds(bounds);
}
google.maps.event.addDomListener(window, "load", initMap);
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map"></div>
Here is how I do it (a small snippet of my code) in jQuery, just pass your map into the function:
function (mapInfo) {
var noMarkers = false;
if (!mapInfo.markers || mapInfo.markers.length === 0) {
noMarkers = true;
var marker = new google.maps.Marker({
position: { lat: YOUR_DESIRED_HOME_POINT, lng: YOUR_DESIRED_HOME_POINT },
optimized: false
});
mapInfo.markers.push(marker);
}
var bounds = new google.maps.LatLngBounds();
// Create bounds from markers
$.each(mapInfo.markers, function (index, item) {
var latlng = mapInfo.markers[index].getPosition();
bounds.extend(latlng);
});
// Google wants to zoom ALL the way in for only one marker, so if there is only one, we'll back it out a bit
if (bounds.getNorthEast().equals(bounds.getSouthWest())) {
var adjustBy = noMarkers ? 20.5 : 0.005;
var extendNortheast = new google.maps.LatLng(bounds.getNorthEast().lat() + adjustBy, bounds.getNorthEast().lng() + adjustBy);
var extendSouthwest = new google.maps.LatLng(bounds.getNorthEast().lat() - adjustBy, bounds.getNorthEast().lng() - adjustBy);
bounds.extend(extendNortheast);
bounds.extend(extendSouthwest);
}
google.maps.event.addListenerOnce(mapInfo.map, 'bounds_changed', function () {
var zoom = mapInfo.map.getZoom();
if (zoom > 18) {
mapInfo.map.setZoom(16);
}
});
mapInfo.map.fitBounds(bounds);
}

Adding eventlistener to javascript array

I'm trying to put my markers on google maps and add an InfoWindow to each single marker. I'm getting Cannot read property 'name' of undefined on this line after I click on one of the markers:
markers[i].name.open(map, marker);
Here's the complete script:
function initMap() {
var map = new google.maps.Map(document.getElementById("map"), {
zoom: 3,
// zoom in on current location if available (not done yet...)
center: new google.maps.LatLng(5,5)
});
var markers = [
// put all markers in a markers array
#foreach ($markers as $marker)
new google.maps.Marker({
position: { lat: {{$marker->x}}, lng: {{$marker->y}} },
// infowindow for each marker with its name
name: new google.maps.InfoWindow({
content: "{{$marker->name}}"
})
}),
#endforeach
];
for (var i = 0; i < markers.length; i++) {
// add eventlistener for the infowindow we added earlier
google.maps.event.addListener(markers[i], 'click', function() {
markers[i].name.open(map, marker);
});
// add marker to map
markers[i].setMap(map);
}
}
I'm using Laravel 5.1 with the Blade templating engine.
This works (this in the click listener refers to the google.maps.Marker that was clicked):
for (var i = 0; i < markers.length; i++) {
// add eventlistener for the infowindow we added earlier
google.maps.event.addListener(markers[i], 'click', function() {
this.name.open(map, this);
});
// add marker to map
markers[i].setMap(map);
}
proof of concept fiddle
code snippet:
function initMap() {
var map = new google.maps.Map(document.getElementById("map"), {
zoom: 3,
// zoom in on current location if available (not done yet...)
center: new google.maps.LatLng(5, 5)
});
var markers = [
// put all markers in a markers array
// #foreach ($markers as $marker)
// New York, NY, USA (40.7127837, -74.00594130000002)
new google.maps.Marker({
position: {
lat: 40.7127837,
lng: -74.0059413
},
// infowindow for each marker with its name
name: new google.maps.InfoWindow({
content: "New York, NY, USA"
})
}),
// Newark, NJ, USA (40.735657, -74.1723667)
new google.maps.Marker({
position: {
lat: 40.735657,
lng: -74.1723667
},
// infowindow for each marker with its name
name: new google.maps.InfoWindow({
content: "Newark, NJ, USA"
})
}),
// Baltimore, MD, USA (39.2903848, -76.61218930000001)
new google.maps.Marker({
position: {
lat: 39.2903848,
lng: -76.6121893
},
// infowindow for each marker with its name
name: new google.maps.InfoWindow({
content: "Baltimore, MD, USA"
})
}),
// #endforeach
];
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < markers.length; i++) {
// add eventlistener for the infowindow we added earlier
google.maps.event.addListener(markers[i], 'click', function() {
this.name.open(map, this);
});
// add marker to map
markers[i].setMap(map);
bounds.extend(markers[i].getPosition());
}
map.fitBounds(bounds);
}
google.maps.event.addDomListener(window, "load", initMap);
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map"></div>
try this ?
for (var i = 0; i < markers.length; i++) {
// add eventlistener for the infowindow we added earlier
(function(i) {
google.maps.event.addListener(markers[i], 'click', function() {
//console.log(markers[i])
markers[i].name.open(map, markers[i]);
});
// add marker to map
markers[i].setMap(map);
})(i);
}

Plotting two objects addresses on map.how to set two different design balloons for two objects?

<script>
function drawMap(){
var balloon = new google.maps.InfoWindow();
var mapOptions = {
center: coords[0],
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
con = con.replace(/[,;]$/,'');
var mystring =con;
var splits = mystring.split(",");
type = type.replace(/[,;]$/,'');
var mystring1 =type;
var splits1 = mystring1.split(",");
var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
for(var i = 0; i < coords.length; ++i){
var marker = new google.maps.Marker({map: map, position: coords[i], title:splits1[i]+'-'+splits[i], zIndex:i});
google.maps.event.addListener(marker, 'click', (function (marker, i) {
return function () {
var index = this.zIndex;
balloon.setContent('<b>'+splits1[i]+'</b><br/>'+splits[i]);
balloon.open(map, marker);
}
})(marker, i));
markers.push(marker);
}
}
geocodeClientSide();
</script>
In Above code Split1[i] output returns as either "account" or "lead" .
I want to keep different design images for plotting account and lead .
Currently i am getting red color balloon by default ?
How can i do that ?
Thanks in advance
Asmentioned in google api In new google.maps.Marker().
please check this example. Here we are using two icons, 1 dotted black, and other brown.
var map;
var locations = [{
position: {
lat: -25.363,
lng: 131.044
},
icon: 'http://icons.iconarchive.com/icons/icons8/ios7/256/Maps-Location-icon.png',
}, {
position: {
lat: -28.363,
lng: 135.044,
},
icon: 'http://icons.iconarchive.com/icons/graphicloads/100-flat/256/location-icon.png',
}];
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644},
zoom: 4,
center: locations[0].position
});
for (var index in locations) {
var image = new google.maps.MarkerImage(
locations[index]['icon'],
null, /* size is determined at runtime */
null, /* origin is 0,0 */
null, /* anchor is bottom center of the scaled image */
new google.maps.Size(20, 20));
var marker = new google.maps.Marker({
position: locations[index].position,
map: map ,
icon: image,
});
}
}
$(document).ready(function() {
initMap();
});
#map {
width: 300px;
height: 300px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map"></div>

Categories

Resources