infoWindow and center on click outside map - google-maps

I have been playing around with Google Maps, and would like to center on a marker and open the appropriate infoWindow when I click on an element outside the map.
For example I have;
<div id="map"></div>
Store A
Opening Hours: 10-10
Store B
Opening Hours: 10-4
Store C
Opening Hours: 9-9
Store D.
Opening Hours: 8-9
I would like it to work, when I click on one of the stores in the list (outside of the map), it call the appropriate marker, centres on it and opens the attached infoWindow.
The infoWindow is working on marker click.
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 11,
center: {
lat: -33.800426,
lng: 142.038494
}
});
setMarkers(map);
}
// Data for the markers consisting of a name, a LatLng and a zIndex for the
// order in which these markers should display on top of each other.
var stores = [
['A', -33.771624, 142.888128, 1],
['B', -33.843956, 142.994875, 2],
['C', -33.818086, 142.995699, 3],
['C', -33.812697, 143.229200, 4],
];
function setMarkers(map) {
// Adds markers to the map.
for (var i = 0; i < stores.length; ++i) {
var store = stores[i];
const marker = new google.maps.Marker({
position: {
lat: store[1],
lng: store[2]
},
map: map,
animation: google.maps.Animation.DROP,
title: store[0],
zIndex: store[3],
});
attachStoreTitle(marker);
}
}
// Attaches an info window to a marker with the provided message. When the
// marker is clicked, the info window will open with message.
function attachStoreTitle(marker) {
var infowindow = new google.maps.InfoWindow({
content: marker.title
});
marker.addListener('click', function() {
infowindow.open(marker.get('map'), marker);
});
}
initMap()

Completed fiddle at https://jsfiddle.net/00e58pba/8/
Attach event listener to markers and then open correct infoWindow -
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
// Close all other infoboxes
for (var j = 0; j < markers.length; j++) {
markers[j].infobox.close(map);
}
// Open correct info box
markers[i].infobox.open(map, markers[i]);
}
})(marker, i));

If I've understood what you're asking, I think you should be able to do this:
marker.addListener('click', function() {
infowindow.open(marker.get('map'), marker);
marker.get('map').setCenter(this.getPosition());
});

Related

Google map marker click event using angular

I want create a click event using angular js google map api.
On click on the marker I want to call a function without opening the info window.
How can I do this ?
$scope.map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center: { lat: parseFloat(Center_lat) , lng: parseFloat(center_lang) }
});
$scope.infowindow = new google.maps.InfoWindow({
// content: ''
});
angular.forEach($scope.panoramas, function(value, index) {
var latLang = $scope.panoramas[index].project_latLng ;
// console.log(latLang)
var LatLngArr = latLang.split(",");
var lat = LatLngArr[0];
var lang = LatLngArr[1];
console.log("lat " ,lat);
var marker = new google.maps.Marker({
position: new google.maps.LatLng(parseFloat(lat), parseFloat(lang)),
map: $scope.map,
icon:"images/map-circle.png",
draggable:true,
label: {
color: 'black',
fontWeight: 'bold',
text: $scope.panoramas[index].panoId,
},
title: $scope.panoramas[index].panoId
});
var content = '<a ng-click="ShowCenterPano(' + index + ')" class="btn btn-default">View details</a>';
var compiledContent = $compile(content)($scope)
google.maps.event.addListener(marker, 'click', (function(marker, content, scope) {
return function() {
scope.infowindow.setContent(content);
scope.infowindow.open(scope.map, marker);
};
})(marker, compiledContent[0], $scope));
$scope.ShowCenterPano = function(index) {
// alert(JSON.stringify($scope.panoramas[index]));
}
Here Info window is opening. How can I remove the info window and directly call the ShowCenterPano() function.
Everything you want to happen when you click on the marker is inside the listener.
I think you are making your code needlessly complicated. Just put a listener on your marker marker.addListener('click', function() {}); and in this function you run ShowCenterPano()
And the reason the infowindow is opening is because you ask it to open with this line of code scope.infowindow.open(scope.map, marker);

Google Nearby change type on click

I'm working on a project where I'd like to show the choosen event on google maps with some additional information. (ex. all gas stations radius 2km).
Google doesn't allow a nearby search with multiple types.
Restricts the results to places matching the specified type. Only one type may be specified (if more than one type is provided, all types following the first entry are ignored).
So for now I'd like to change the type (ex. gas_station or store) if I click to a custom button I added.
(used the google document example)
Screenshot: http://imgur.com/qYwLuw4
Question:
Which is the best way to change the type and refresh the map with the new information?
I'd like to present you our solution.
We wrote a clear() and a showType() function, which will erase all markers and let the right ones appear on click. By the way we give the button a state class called "selected" for CSS styling.
We didn't find a solution to show both (washstation AND fuelstation).
<script type="text/javascript">
var map;
var infowindow;
var service;
var eventLocation = {lat: <?= $arrCoordinates['latitude']?>, lng: <?= $arrCoordinates['longitude']?>};
var markers = [];
var wash = document.getElementById('wash'); //washbutton
var fuel = document.getElementById('fuel'); //fuelstation button
function initMap() {
map = new google.maps.Map(document.getElementById('eventmap'), {
center: eventLocation,
zoom: 13,
});
infowindow = new google.maps.InfoWindow();
service = new google.maps.places.PlacesService(map);
showType('gas_station');
fuel.classList.add("selected");
typeControl(map);
}
// Type control function
function typeControl ( map ) {
google.maps.event.addDomListener(fuel, 'click', function() {
wash.classList.remove("selected");
fuel.classList.remove("selected");
clear()
showType('gas_station')
this.classList.add("selected");
});
google.maps.event.addDomListener(wash, 'click', function() {
wash.classList.remove("selected");
fuel.classList.remove("selected");
clear()
showType('car_wash')
this.classList.add("selected");
});
}
function showType(type) {
service.nearbySearch({
location: eventLocation,
radius: 10000,
type: [type]
}, callback);
}
function clear() {
markers.forEach(marker => marker.setMap(null));
markers = [];
}
function callback(results, status) {
clear()
if (status === google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
createTuningEventMarker();
}
}
function createTuningEventMarker(place) {
var eventLocation = {lat: <?= $arrCoordinates['latitude']?>, lng: <?= $arrCoordinates['longitude']?>};
var eventIcon = {
url: 'https://www.foo.lol/img/icons/pin.svg',
// This marker is 20 pixels wide by 32 pixels high.
scaledSize: new google.maps.Size(60, 60),
// The origin for this image is (0, 0).
origin: new google.maps.Point(0,0),
// The anchor for this image is the base of the flagpole at (0, 32).
anchor: new google.maps.Point(30,60)
};
var marker = new google.maps.Marker({
map: map,
icon:eventIcon,
position: eventLocation
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent('<?= $event['name']?>');
infowindow.open(map, this);
});
}
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
markers.push(marker);
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(place.name + "<br>Adress: " + place.vicinity);
infowindow.open(map, this);
});
}
</script>

Google Maps, open info window after click on a link

i have this code to display a google map:
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script type="text/javascript">
function initialize() {
var mapOptions = {
zoom: 10,
center: new google.maps.LatLng(40.714364, -74.005972),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("googlemap"), mapOptions);
var locations = [
['New York', 40.714364, -74.005972, 'http://www.google.com/intl/en_us/mapfiles/ms/micons/green-dot.png']
];
var marker, i;
var infowindow = new google.maps.InfoWindow();
google.maps.event.addListener(map, 'click', function() {
infowindow.close();
});
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map,
icon: locations[i][3]
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<div id="googlemap" style="width: 100%; height: 500px;"></div>
Open Info Window
That's not the final code, because i want add more markers.
The problem is, that i need external links to open the info window of a marker.
For Example:
Link 1 opens the info window from marker 1
Link 2 opens the info window from marker 2
etc...
I need a link something like this:
Open Info Window One
Here is my code in jsfiddle:
http://jsfiddle.net/fJ4jG/3/
I found couple of solutions, but i don't know how to use this code together with my code.
It should work like this:
http://www.geocodezip.com/v3_MW_example_map2.html
Thanks for every help!
What that example does is it creates an array where it stores the markers. So when the markers are created, they get pushed to that markers array. When you click on the link you send an index with the function that is a reference to the marker in the array.
So JavaScript looks like this:
var markers = [];
// The array where to store the markers
function initialize() {
var mapOptions = {
zoom: 10,
center: new google.maps.LatLng(40.714364, -74.005972),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("googlemap"), mapOptions);
var locations = [
['New York', 40.714364, -74.005972, 'http://www.google.com/intl/en_us/mapfiles/ms/micons/green-dot.png']
];
var marker, i;
var infowindow = new google.maps.InfoWindow();
google.maps.event.addListener(map, 'click', function() {
infowindow.close();
});
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map,
icon: locations[i][3]
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
// Push the marker to the 'markers' array
markers.push(marker);
}
}
google.maps.event.addDomListener(window, 'load', initialize);
// The function to trigger the marker click, 'id' is the reference index to the 'markers' array.
function myClick(id){
google.maps.event.trigger(markers[id], 'click');
}
And in your HTML a tag you add the myClick function like this:
Open Info Window
Example: http://jsfiddle.net/fJ4jG/9/
As in my example.
add a global array to save references to the google.maps.Marker objects:
var gmarkers = [];
push the markers onto that array as you create them
gmarkers.push(marker);
trigger the "click" event on the desired marker:
Open Info Window
jsfiddle
use this code i already tried it
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(locations[i][0]);
infoWindow.open(map, marker);
});

Google Map Marker Clusters

i've been trying to implement a new feature on one of my Google maps (MarkerClusterer), but i am not quite there yet.
It is running OK, but not smoothly and it would be great if you would look through the code and give me any tips/advice.
I am running a test here: (Link removed)
Please let me know if you need anymore info.
Any help is appreciated :)
You seem to be doing an awful lot within the loop that creates your markers. For instance you should only need to do var markerCluster = new MarkerClusterer(...) after that loop, not within every iteration of it!
Ok, here I've simply moved that line out of your loop.
for (var i = 0; i < mapLocationsdata.businesses.length; i++) {
var businesses = mapLocationsdata.businesses[i];
var pos = new google.maps.LatLng(businesses.lat, businesses.lng);
var marker = new google.maps.Marker({
position: pos,
map: map,
title: businesses.company,
icon: placemarker[businesses.placemaker],
clickable: true,
draggable:false,
animation: google.maps.Animation.DROP
});
markers.push(marker);
(function(i, marker){
var infobox = new google.maps.InfoWindow({
content:
//This creates the content inside the popup info window when clicked
'<div class="info"><div class="info1"><h4>'
+businesses.company+
'</h4></div><div class="infotel">'
+businesses.itemAdresse+businesses.itemPostBy+businesses.itemTlf+businesses.itemEmail+businesses.itemWeb+
'</div><div class="clearfix"></div></div>',
});
//This function opens the info box and toggles the icon bounce
marker.addListener('click', function() {
infobox.open(map, marker);
toggleBounce(map, marker);
});
//This function stops the bouncs on the icon once the infowindow is closed
infobox.addListener('closeclick', function() {
toggleBounce(map, marker);
});
// POSSIBLY THIS FUNCTION COULD BE MOVED OUT OF THE LOOP TOO
//This makes them bounce when clicked
function toggleBounce() {
if (marker.getAnimation() != null) {
marker.setAnimation(null);
} else {
marker.setAnimation(google.maps.Animation.BOUNCE);
}
}
})
//The marker loop generates all of the markers
// NO IDEA WHAT THE POINT OF THIS LINE IS:
(i, marker);
//Associate the styled map with the MapTypeId and set it to display.
map.mapTypes.set('map_style', styledMap);
map.setMapTypeId('map_style');
}
var markerCluster = new MarkerClusterer(map, markers, {
gridSize: 60,
minimumClusterSize: 2,
calculator: function(markers, numStyles) {
if (markers.length >= 50) return {text: markers.length, index: 3}; // red
if (markers.length >= 5) return {text: markers.length, index: 2}; // yellow
return {text: markers.length, index: 0}; } // blue
});

Google Maps API V3 - add event listener to all markers?

There's got to be a way to add a listener to ALL MARKERS, currently I'm adding a listener to each one using a loop which feels really wrong...
This feels wrong:
google.maps.event.addListener(unique_marker_id, 'click', function(){
//do something with this marker...
});
In both Marker and MarkerWithLabel case, you might just as well use the this keyword to refer the object to which the event handler is attached:
google.maps.event.addListener(marker, 'click', function () {
// do something with this marker ...
this.setTitle('I am clicked');
});
this here is referring to the particular marker object.
You need to add the listener to each marker, but you can make it easy by e.g. defining a function like
function createMarker(pos, t) {
var marker = new google.maps.Marker({
position: pos,
map: m, // google.maps.Map
title: t
});
google.maps.event.addListener(marker, 'click', function() {
alert("I am marker " + marker.title);
});
return marker;
}
and call it appropriately:
var m1 = createMarker(new google.maps.LatLng(...), "m1");
var m2 = createMarker(new google.maps.LatLng(...), "m2");
or in a loop, etc.
If you're using GoogleMaps v3.16 or later, you can add the event handler to the whole map.data layer.
var map = new google.maps.Map(document.getElementById("map-canvas"), options);
map.data.loadGeoJson('http://yourserver.com/path/to/geojson.json');
map.data.addListener('click', function(e) {
// this - instance of the layer object, in this case - map.data
// e.feature - instance of the feature object that initiated the event
// e.latLng - the position of the event
});
see: https://developers.google.com/maps/documentation/javascript/examples/layer-data-event
I managed to do this using FusionTablesLayer. It's a bit of work setting everything up correctly, but once you're done, it's ultra-fast, even with thousands of markers.
You basically create a public table in Google Docs and query it from your webpage. The map is pre-generated on Googles' servers, which is why it performs so well.
A complete demo page:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Google Maps Demo</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<meta charset="UTF-8">
<style type="text/css">
html, body, #map_canvas
{
margin: 0;
padding: 0;
height: 100%;
}
</style>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
function initialize()
{
var denmark = new google.maps.LatLng(56.010666, 10.936890);
map = new google.maps.Map(document.getElementById('map_canvas'), {
center: denmark,
zoom: 7,
mapTypeId: 'roadmap'
});
layer = new google.maps.FusionTablesLayer({
query: {
select: 'Coordinates',
from: '1234567'
}
});
layer.setMap(map);
google.maps.event.addListener(layer, 'click', function (event) {
alert('Hello World!'); });
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas"></div>
</body>
</html>
Check out this article for more info, "Too Many Markers!" by Luke Mahe and Chris Broadfoot from the Google Geo APIs Team.
I managed to get an answer here:
Google Maps and Their Markers
and a demo here:
http://jsfiddle.net/salman/bhSmf/
This simplest way is this:
google.maps.event.addListener(marker, 'click', function() {
var marker = this;
alert("Tite for this marker is:" + this.title);
});
To Expand on Jiri answer purley for those searching who also wish to add a custom label etc. In the spirit of Jiri post, in shorthand version:
var m1 = createMarker({lat: -25.363, lng: 131.044}, "m1", "<div id=\"content\"><div id=\"siteNotice\"></div> <h1 id=\"firstHeading\" class=\"firstHeading\">m1</h1> <div id=\"bodyContent\">Some info</div> </div>");
function createMarker(pos, t, d) {
var marker = new google.maps.Marker({
position: pos,
map: map,
title: t
});
google.maps.event.addListener(marker,"click", function() {
alert("I am marker " + marker.title);
new google.maps.InfoWindow({ content: d }).open(map, marker);
});
return marker;
}
Remove alert, just there to show the action etc. as with Jiri's info, you can add m2, m3 etc. I thought this simply finished things off.
/* Note: I have a set of data, and it is named by the variable data.
* The variable data is an array
*/
//Here I get the length of the data
var dataLength = data.length;
//Then I iterate through all my pieces of data here
//NOTICE THAT THE KEYWORD let IS SO IMPORTANT HERE
for(let markerIterator = 0; markerIterator < dataLength; markerIterator++) {
/* This creates a new google maps marker based on my data's latitude and
* longitude
*/
var marker = new google.maps.Marker({
position: { lat: data[markerIterator].latitude, lng:
data[markerIterator].longitude },
map: map
});
google.maps.event.addListener(marker, 'click', function () {
/* This will spit out the unique markerIterator value for each marker when
* clicked. It is a unique value because I defined markerIterator with the
* keyword let!
*/
console.log(markerIterator);
// Use the keyword this to refer to each unique marker, for example:
map.setCenter(this.getPosition());
});
}
What i've Done is, when adding new marker on map and before pushing it into markers = [] array, i just add listener to it marker.addListener('click', () => { // Do Something here});
Complete Code:
// Adds a marker to the map and push to the array.
function addMarker(location) {
var marker = new google.maps.Marker({
position: location,
icon: {
url: "http://maps.google.com/mapfiles/ms/icons/blue-dot.png"
},
animation: google.maps.Animation.DROP,
map: map
});
marker.addListener("click",
() => {
console.log("Marker Click Event Fired!");
});
markers.push(marker);
}
LINK i followed!
It was really hard for me to find a specific answer to my need. But this one is working now and everywhere for me!
Regards! :)
var map;
function initialize_map(locations) {
var options = {
zoom: 8,
center: new google.maps.LatLng(59.933688,30.331879),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map-canvas"), options);
var bounds = new google.maps.LatLngBounds();
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][lat], locations[i][lng]),
map: map,
title: locations[i][title]
});
set_event(marker);
bounds.extend(marker.position);
}
map.fitBounds(bounds);
}
function set_event(marker) {
google.maps.event.addListener(marker, 'click', function() {
// do something with this marker ...
});
}
You can do something like this:
function setMarkers(map, locations) {
var image = ['circle_orange.png','circle_blue .png'];
for (var i = 0; i < locations.length; i++) {
var stations = locations[i];
var myLatLng = new google.maps.LatLng(stations[1], stations[2]);
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
icon: image[stations[3]],
title: stations[0],
zIndex: stations[3],
optimized: false
});
var infowindow = new google.maps.InfoWindow({
content: "No data available"
});
google.maps.event.addListener(marker, 'mouseover', function() {
infowindow.setContent("We can include any station information, for example: Lat/Long: "+ stations[1]+" , "+stations[2]);
infowindow.open(map, this);
});
}
}