How to open web links from some Google Maps markers? - javascript

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>

Related

Cannot remove markers from google maps api

The markers in my program just wont remove with the deleteMarkers() function
CSS:
#map-canvas {
margin: 0;
padding: 0;
height: 100%;
}
HTML:
<div style="height:500px; width:750px;">
<div id="map-canvas"></div>
</div>
<select class="form-control" name="dateSelect" id="dateSelect" onchange="dateSelect_Event();"></select>
Javascript:
var map; <--- global variables
var locations = [];
var lat_get = '';
var long_get = '';
var marker=[];
var infowindow;
function initMap() {
map = new google.maps.Map(document.getElementById('map-canvas'), {
center: {lat: 7.072617, lng: 125.599494},
mapTypeId: google.maps.MapTypeId.ROADMAP,
zoom: 13,
});
};
function deleteMarkers() {
for (var i = 0; i < marker.length; i++ ) {
marker[i].setMap(null);
}
marker.length = 0;
}
function dateSelect_Event() {
deleteMarkers();
infowindow = new google.maps.InfoWindow({});
var locationsRef = firebase.database().ref("location");
locationsRef.on('child_added', function(snapshot) {
var data = snapshot.val();
marker = new google.maps.Marker({
position: {
lat: parseFloat(data.latitude),
lng: parseFloat(data.longitude)
},
map: map
});
marker.addListener('click', (function(data) {
return function(e) {
infowindow.setContent(this.getPosition().toUrlValue(6));
infowindow.open(map, this);
}
}(data)));
marker.setMap(map);
});
}
Firebase:
-databaseName
--location
---latitude
---longitude
I just use firebase to get the lat and long on every change of the html select option and it work perfectly. The problem this time is it can't delete the markers. Should I do the deleteMarkers differently?
Thanks to #StackSlave's answer. I was able to successfully remove it by creating and pushing the google_marker to the global marker variable.
function dateSelect_Event() {
deleteMarkers();
infowindow = new google.maps.InfoWindow({});
var locationsRef = firebase.database().ref("location");
locationsRef.on('child_added', function(snapshot) {
var data = snapshot.val();
var google_marker = new google.maps.Marker({
position: {
lat: parseFloat(data.latitude),
lng: parseFloat(data.longitude)
},
map: map
});
google_marker.addListener('click', (function(data) {
return function(e) {
infowindow.setContent(this.getPosition().toUrlValue(6));
infowindow.open(map, this);
}
}(data)));
marker.push(google_marker);
});
marker.setMap(map);
}

google maps info windows opening at extreme left instead of provided position

I am using google maps API to make some custom markers and i want to open a custom info window. I have been trying to set the position of the info window but its always opening on the extreme top left.
var markers = [
[37.09024, -95.712891, "images/white-star.png"],
[40.4173, -82.9071, "images/purple-star.png"],
[31.9686, -99.9018, "images/yellow-star.png"],
];
for (i = 0; i < markers.length; i++) {
var position = new google.maps.LatLng(markers[i][0], markers[i][1]);
var icon = markers[i][2];
marker[i] = infowindow = new google.maps.InfoWindow({
content: html,
pixelOffset: new google.maps.Size(200, 0)
});
marker[i] = new google.maps.Marker({
position: position,
icon: icon,
map: map,
}).addListener('mouseover', function() {
infowindow.open(map, marker[i]);
});
}
I think your problem lies how to create marker and info window in your code.To create multiple markers in map, see code below .
Fiddle demo
function initMap() {
var myLatLng = {
lat: 40.4173,
lng: -82.9071
};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: myLatLng
});
var markers = [
[37.09024, -95.712891, "images/white-star.png"],
[40.4173, -82.9071, "images/purple-star.png"],
[31.9686, -99.9018, "images/yellow-star.png"],
];
for (i = 0; i < markers.length; i++) {
(function(markers) {
var position = new google.maps.LatLng(markers[0], markers[1]);
var icon = markers[2];
var infowindow = new google.maps.InfoWindow({
content: 'html',
pixelOffset: new google.maps.Size(200, 0)
});
var markerss = new google.maps.Marker({
position: position,
map: map,
//icon: icon,
});
google.maps.event.addListener(markerss, 'click', function() {
infowindow.open(map, markerss);
});
})(markers[i]);
}
}
marker[i] is not defined in this line:
infowindow.open(map, marker[i]);
Without a defined anchor, the infowindow ends up in the upper left hand corner of the map.
You can use this for the anchor in the mouseover event handler function:
infowindow.open(map, this);
You probably also want to remove the:
pixelOffset: new google.maps.Size(200, 0)
proof of concept fiddle
code snippet:
var geocoder;
var map;
function initialize() {
var 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
});
var markers = [
[37.09024, -95.712891, "images/white-star.png"],
[40.4173, -82.9071, "images/purple-star.png"],
[31.9686, -99.9018, "images/yellow-star.png"],
];
var bounds = new google.maps.LatLngBounds();
for (i = 0; i < markers.length; i++) {
var html = "marker";
var position = new google.maps.LatLng(markers[i][0], markers[i][1]);
var icon = markers[i][2];
var infowindow = new google.maps.InfoWindow({
content: html,
// pixelOffset: new google.maps.Size(200, 0)
});
var marker = new google.maps.Marker({
position: position,
// icon: icon,
map: map,
}).addListener('mouseover', function() {
infowindow.open(map, this);
});
bounds.extend(position);
}
map.fitBounds(bounds);
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map_canvas"></div>

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