Hi I am trying to integrate gmap with my website.But by default the infowindow is opened.I want to open the infowindow after clicking on the markers.How to close the infowindow on page load?
function initialize() {
if (GBrowserIsCompatible()) {
var map = new GMap2(document.getElementById("map_canvas"));
map.setCenter(new GLatLng(22.4642600, 70.0690540), 6);
map.addControl(new GSmallMapControl());
map.addControl(new GMapTypeControl());
map.addMapType(G_SATELLITE_3D_MAP);
for (var i = 0; i < newpoints.length; i++) {
var point = new GPoint(newpoints[i][1], newpoints[i][0]);
var popuphtml = newpoints[i][4];
var post_url = newpoints[i][5];
var addr = newpoints[i][6];
var marker = createMarker(point, newpoints[i][2], popuphtml, post_url, addr);
map.addOverlay(marker);
}
}
}
function createMarker(point, icon, popuphtml, post_url, addr) {
var popuphtml = '<div id="popup">' + popuphtml + '<div><a href=' + post_url + '>Link</a></div></div>';
var marker = new GMarker(point);
marker.openInfoWindowHtml(popuphtml);
GEvent.addListener(marker, "click", function () {
marker.openInfoWindowHtml(popuphtml);
});
return marker;
}
Remove this line
marker.openInfoWindowHtml(popuphtml);
so it becomes
function createMarker(point, icon, popuphtml, post_url, addr) {
var popuphtml = '<div id="popup">' + popuphtml + '<div><a href=' + post_url + '>Link</a></div></div>';
var marker = new GMarker(point);
GEvent.addListener(marker, "click", function () {
marker.openInfoWindowHtml(popuphtml);
});
return marker;
}
you were calling the openInfoWindowHtml method immediately ... now its only called when the click event of the marker occurs
Note
You are using Google Maps V2 ... this is the message from google related to V2
Note: The Google Maps Javascript API Version 2 has been officially deprecated as of May 19, 2010. The V2 API will continue to work as per our deprecation policy, but we encourage you to migrate your code to version 3 of the Maps Javascript API.
remove the marker.openInfoWindowHtml(popuphtml); after var marker = new GMarker(point);
Related
I have an array like this deviceId = [005305230001JIZZZZ, 085835360001NBGJZZ, 085835360002NBGJZZ].
The info window should show the deviceId and be displayed based on which marker is clicked. I started looking at JavaScript only a few days back and can't understand how the functions work and dont have the time right now to learn becauseI have to get this done. I saw a few implementations on this, but I think they have done the adding multiple markers differently using functions, I think. I couldn't understand it so I used for loop.
The latArray and lngArray have something like this [12.1456,12.5256,11.566] and [72.145,72.4557,75.23535]
I cant figure out how to add info windows for corresponding markers.
This is the code for map:
function initMap() {
var bounds = new google.maps.LatLngBounds();
var mapDiv = document.getElementById('map');
var map = new google.maps.Map(mapDiv);
map.setCenter(new google.maps.LatLng(latArray[0],lngArray[0]));
map.setZoom(18);
for(i=0;i<latArray.length;i++)
{
marker = new google.maps.Marker({
position: new google.maps.LatLng(latArray[i],lngArray[i]),
map: map,
title:"This is the place.",
// icon:"phone4.png"
});
//bounds.extend(marker.getPosition());
console.log(latArray);
console.log(lngArray);
}
//map.fitBounds(bounds);
var infoWindow = new google.maps.InfoWindow({
content: contentString
});
marker.addListener('click', function() {
infoWindow.open(map, marker);
});
}
How to show info window of corresponding markers.
This is content for marker:
contentString = '<div id = "content>'
+'<p style = "color:#000000">DeviceID<p>' +
'<p>'+ deviceId[i] + '<br></p>' //deviceId is the array with content
+ '</div>'
I read something about closures but didn't understand. Please help
Edit: I just tried this. I'm getting js?callback=initMap:34 InvalidValueError: setPosition: not a LatLng or LatLngLiteral: not an Object
What i tried:
var markerArray=[];
for(i=0;i<latArray.length;i++)
{
markerArray.push("new google.maps.LatLng("+ latArray[i]+","+lngArray[i]+")");
console.log(markerArray[i]);
}
console.log(markerArray[0]);
for(i=0;i<latArray.length;i++)
{
marker = new google.maps.Marker({
position: markerArray[i],
map: map,
title:"This is the place.",
// icon:"phone4.png"
});
var infoWindow = new google.maps.InfoWindow({
content: contentString[i]
});
marker.addListener('click', function(marker,contentString) {
infoWindow.open(map, marker);
});
}
So I will not bother you with the explanation how closures work (as you are saying your not interested in it now), I just supply you the solution:
// Your arrays with geo informations
var latArray = [-25.363, -26.263, -25.163];
var lngArray = [131.044, 131.144, 132.044];
// Your array with device information
var deviceIdArray = ["AAA", "BBB", "CCC"];
// Just create map according to the first geo info
var map = new google.maps.Map(document.getElementById("map"), {
center: {lat: latArray[0], lng: lngArray[0]},
zoom: 6
});
// Loop throuhg all geo info
latArray.forEach(function(lat, i) {
// For each one create info window
var infoWindow = new google.maps.InfoWindow({
content: '<div id="content>'
+ '<p style="color:#000000">DeviceID<p>'
+ '<p>'+ deviceIdArray[i] + '</p>'
+'</div>'
});
// For each one create marker
var marker = new google.maps.Marker({
map: map,
position: {lat: latArray[i], lng: lngArray[i]}
});
// Click on the currently created marker will show the right info window
marker.addListener("click", function() {
infoWindow.open(map, marker);
});
});
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
}
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3"></script>
<div id="map"></div>
Take a look at my function with map. It takes json object with some data from PHP and 'translate' it into array and then adds content to multiple markers (it is not dynamic in real time - you have to reload page). In addition it has a search box (which opens certain info window). If you don't understand do not hestitate to ask :).
//check if document is fully loaded, seetting a container for ajax call results
$(document).ready(function() {
var tablica = [];
// ajax call for action preparing set of names, descriptions, coords and slugs needed to render deatiled markers on map
$.ajax({
url: 'map/json_prepare',
dataType: 'json',
success: function(response) {
var obj = JSON && JSON.parse(response) || $.parseJSON(response);
obj.forEach(function(item, index, array)
{
tablica.push(item);
});
//call a function rendering a map itself
var map;
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 50.06561980, lng: 19.946850},
zoom: 12
});
////////////////////////////////////////////////////////////////////////////////////////////////////
// LOOP ADDING MARKERS FROM DB WITH PROPER INFO WINDOWS (DESCRIPTION AND LINKS)
// Add a markers reference
var markers = [];
$.each(tablica, function( key, value ) {
//markers
var myLatLng = {lat: value[1], lng: value[2]};
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: value[0],
clickable: true,
animation: google.maps.Animation.DROP,
adress: value[5]
});
//infowindows
marker.info = new google.maps.InfoWindow ({
content: '<h1>'+ value[0] + '</h1>' + '<br>' + '<br>' + value[3] + '<br>' + value[5] +'<br>' + '<br>' + '' + 'Details' + '<br/>' +
'' + 'Take part in' + '<br>'
});
//eventlistener - after click infowindow opens
google.maps.event.addListener(marker, 'click', function() {
marker.info.open(map, marker);
});
//event listener - after dblclick zoom on certain event is set
google.maps.event.addListener(marker, 'dblclick', function() {
map.setZoom(18);
map.setCenter(marker.getPosition());
});
markers.push(marker);
});
// End of loop adding markers from db.
///////////////////////////////////////////////////////////////////////////////////////////////////////////
///additional event listener - rightclick to get back default zoom
google.maps.event.addListener(map, 'rightclick', function() {
map.setZoom(12);
map.setCenter(map.getPosition());
});
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
//CENTRING MAP AS ALL OF MARKERS IS VISIBLE//
//create empty LatLngBounds object
var bounds = new google.maps.LatLngBounds();
var infowindow = new google.maps.InfoWindow();
for (i = 0; i < tablica.length; i++) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(tablica[i][1], tablica[i][2]),
map: map
});
//extend the bounds to include each marker's position
bounds.extend(marker.position);
}
//now fit the map to the newly inclusive bounds
map.fitBounds(bounds);
/////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
///SEARCH_BOX////////
///Here comes part of script adding search box
// Create the search box and link it to the UI element.
// Anchor search box and search button to the map.
var input = document.getElementById('pac-input');
var searchBox = new google.maps.places.SearchBox(input);
var button = document.getElementById('submitSearch');
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
map.controls[google.maps.ControlPosition.TOP_LEFT].push(button);
//replacing polish characters on order to search without necessity typing them
function cleanUpSpecialChars(str)
{
str = str.replace(/[Ą]/g,"A");
str = str.replace(/[ą]/g,"a");
str = str.replace(/[Ę]/g,"E");
str = str.replace(/[ę]/g,"e");
str = str.replace(/[Ć]/g,"C");
str = str.replace(/[ć]/g,"c");
str = str.replace(/[Ł]/g,"L");
str = str.replace(/[ł]/g,"l");
str = str.replace(/[Ń]/g,"N");
str = str.replace(/[ń]/g,"n");
str = str.replace(/[Ó]/g,"O");
str = str.replace(/[ó]/g,"o");
str = str.replace(/[Ś]/g,"S");
str = str.replace(/[ś]/g,"s");
str = str.replace(/[Ź]/g,"Z");
str = str.replace(/[ź]/g,"z");
str = str.replace(/[Ż]/g,"Z");
str = str.replace(/[ż]/g,"z");
return str;
}
//Function, that search in array of markers, one which fits the key word written in searchbox.
$('#submitSearch').click(function() {
//Catching searched word and preparing its value for search process
var toSearch = $(input).val().trim();
toSearch = cleanUpSpecialChars(toSearch);
toSearch = toSearch.toLowerCase();
console.log('Szukana fraza -> ' + toSearch);
var results = [];
if (toSearch.length >=3) {
// Iterate through the array
$.each(markers, function (i, marker) {
//preparing certain elemnts of marker objects for search process
markers[i].title = cleanUpSpecialChars(markers[i].title);
markers[i].adress = cleanUpSpecialChars(markers[i].adress);
markers[i].title = markers[i].title.toLowerCase();
markers[i].adress = markers[i].adress.toLowerCase();
if (markers[i].title.indexOf(toSearch) > -1 || markers[i].adress.indexOf(toSearch) > -1) {
results.push(markers[i]);
}
});
if (results.length < 1) {
console.log ('nic');
$('#message2').slideDown(500, function () {
setTimeout(function () {
$('#message2').slideUp(500);
}, 5000);
});
}
// Close all the infoWindows, before rendering Search results.
markers.forEach(function (marker) {
marker.info.close(map, marker);
});
//Opens infWindows for multiple markers found and set bounds so that all markers found are visible
results.forEach(function (result) {
result.info.open(map, result);
bounds.extend(result.position);
});
map.fitBounds(bounds);
}
else{
//what if user has typed less than three characters in searchbox -> render flash mess.
$("#message").slideDown(500, function(){
setTimeout(function(){
$("#message").slideUp(500);
},5000);
});
}
});
//Enabling key Enter for triggering a search action.
$(input).keypress(function(e){
if(e.which == 13){//Enter key pressed
$('#submitSearch').click();//Trigger search button click event
}
});
},
//////////////////////////////////////////////////////////////////////////////////////////
//obsługa błędu, jeśli nie zostanie wyświetlona mapa
error: function (xhr, ajaxOptions, thrownError) {
console.log(xhr.status);
console.log(thrownError);
console.log(ajaxOptions);
alert('Map is broken. Please try again later.')
}
});
});
It will not qork here because it doesn't contain data from php.
When using google maps api v3, I add a marker to the map with an infowindow with html content and a link w/custom class. I want a jquery trigger to execute upon clicking the link custom class but i've tried many different ways and nothing is working..
Here is my code:
function addMarker(mapArray) {
var techs = mapArray.techs;
var techlinks = mapArray.technamelink;
var address = mapArray.address;
var starttime = mapArray.starttime;
var endtime = mapArray.endtime;
var id = mapArray.id;
var lat = mapArray.lat;
var lng = mapArray.lng;
var client = mapArray.client;
var project = mapArray.project;
var title = techlinks + "<br /> <a class='addresszoom' data-lat='" + lat + "' data-lng='" + lng + "' style='cursor: pointer; font-weight: normal; color: black;'>" + client + "<br />" + starttime + " - " + endtime + "<br />" + address + "</a>";
marker = new google.maps.Marker({ position: new google.maps.LatLng(lat, lng), map: map, title: techs });
marker.id = id;
markersArray.push(marker);
bounds.extend(marker.position);
addInfoWindow(marker, title);
}
function addInfoWindow(marker, message) {
var infoWindow = new google.maps.InfoWindow({
content: message
});
google.maps.event.addListener(marker, 'click', function () {
infoWindow.open(map, marker);
map.panTo(marker.position);
});
google.maps.event.addListener(map, 'click', function () {
infoWindow.close();
});
}
jquery:
$(".addresszoom").click(function() {
var lat = $(this).attr('data-lat');
var lng = $(this).attr('data-lng');
alert('it worked');
map.setCenter(new google.maps.LatLng(lat, lng));
map.setZoom(12);
});
What you want to do is creating a click event handler on a dynamically created element.
Try this :
$(document).on("click", ".addresszoom", function() {
var lat = $(this).attr('data-lat');
var lng = $(this).attr('data-lng');
alert('it worked');
map.setCenter(new google.maps.LatLng(lat, lng));
map.setZoom(12);
});
Documentation
i'm trying to build a WebApp using jQuery Mobile, the Google Maps API and the Geolocation Marker for Google Maps v3. I don't have much experience with js but i'm trying my best.
I create my markers in a for-loop with information from an array. With a little help from Stackoverflow i coul achieve that i click on a marker and get the direction to it.
Now i'm asking you to help me because i want to get the directions only when i click on a Button inside an Infowindow. I tried it with another listener, but i think i dont really get what this is all about.
Here my script:
<script type="text/javascript" charset="UTF-8">
var ren = null;
var GeoMarker = null;
$(document).on('pageshow', '#index',function(e,data){
$('#content').height(getRealContentHeight());
// This is the minimum zoom level that we'll allow
var locations = [
['Museum Wäschefabrik', 52.0212250, 8.5421740,'Hallo hier stehen 1,2 Sätze'],
['Ravensberger Spinnerei', 52.02232686250015, 8.543352720870985, 'cooles Gebäude'],
['Mädchenwohnheim für Spinnerinnen', 52.0205700, 8.5437000, 'Heute IBZ'],
['Mechanische Weberei', 52.0204100, 8.5434700, 'heute Real,-'],
['A. Meyer-Sternberg', 52.0195950, 8.5388760, 'Kontor der Plüschfabrik'],
['Goldmann & Hirschfeld', 52.0189650, 8.5384830, 'Leinen- und Wäschegeschäft (1893)'],
['Gebr. Weiß', 52.0187390, 8.5380260, 'Leinen- und Wäschefabrik, 1940 noch genannt Julius „Israel“ Weiß'],
['C.A. Delius & Söhne', 52.0204570, 8.5357790, 'Leinen- u. Baumwollweberei, Leinen- und Plüsch, Kontor, Fabrik und Lagerräume'],
['Leineweber-Denkmal', 52.0213880, 8.5335790, 'Das Leineweber-Denkmal von 1520'],
['Lueder & Kisker / A. W. Kisker', 52.0224350, 8.5303490, '1974 wurde die Firma A. W. Kisker eingestellt'],
['Herrmann Woermann', 52.0208880, 8.5292260, 'Leinenhandel']
];
var minZoomLevel = 16;
var myLatlng = new google.maps.LatLng(52.0212250,8.5421740);
var map = new google.maps.Map(document.getElementById('map_canvas'), {
zoom: minZoomLevel,
center: new google.maps.LatLng(52.0212250,8.5421740),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var marker, i;
var GeoMarker = new GeolocationMarker();
GeoMarker.setCircleOptions({fillColor: '#ABCDEF'});
google.maps.event.addListener(GeoMarker, 'position_changed', function() {
map.setCenter(this.getPosition());
//map.fitBounds(this.getBounds());
});
google.maps.event.addListener(GeoMarker, 'geolocation_error', function(e) {
alert('There was an error obtaining your position. Message: ' + e.message);
});
GeoMarker.setMap(map);
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
});
google.maps.event.addListener(marker, 'click', (function (marker, i) {
return function () {
infowindow.setContent('<div><h3>' + locations[i][0] + '</h3>' + '<p>' + locations[i][3] + '</p><button id="button" class="ui-btn ui-mini" type="submit">Navigation</button></div>');
infowindow.open(map, marker);
var navButton = document.getElementById('button');
google.maps.event.addListener(navButton, 'click', function() {
if (ren && ren.getMap()) ren.setMap(null);
ren = new google.maps.DirectionsRenderer( {'draggable':false} );
ren.setMap(map);
ren.setPanel(document.getElementById("directionsPanel"));
ser = new google.maps.DirectionsService();
ser.route({ 'origin': GeoMarker.getPosition(), 'destination': marker.getPosition(), 'travelMode': google.maps.DirectionsTravelMode.WALKING},function(res,sts) {
if(sts=='OK')ren.setDirections(res);
})
});
}
})(marker, i));
}
});
if(!navigator.geolocation) {
alert('Your browser does not support geolocation');
}
google.maps.event.addDomListener(window, 'load', initialize);
function getRealContentHeight() {
var header = $.mobile.activePage.find("div[data-role='header']:visible");
var footer = $.mobile.activePage.find("div[data-role='footer']:visible");
var content = $.mobile.activePage.find("div[data-role='content']:visible:visible");
var viewport_height = $(window).height();
var content_height = viewport_height - header.outerHeight() - footer.outerHeight();
if((content.outerHeight() - header.outerHeight() - footer.outerHeight()) <= viewport_height) {
content_height -= (content.outerHeight() - content.height());
}
return content_height;
}
</script>
You need to listen for the domready event of the infowindow. https://developers.google.com/maps/documentation/javascript/reference/info-window#InfoWindow.domready
infoWindow = new google.maps.InfoWindow();
google.maps.event.addListener(infoWindow, 'domready', function() {
// Bind the click event on your button here
});
Hope this helps.
I am using google map which shows marker with information window...in which i display address but i want to show the name as well in information window when a marker is clicked. Any help will be highly appreciated.
function load()
{
var map = new GMap2(document.getElementById("map"));
map.setCenter(new GLatLng(-37.816667,144.966667), 10);
map.addControl(new GSmallMapControl());
map.addControl(new GMapTypeControl());
var geocoder = new GClientGeocoder();
GDownloadUrl("shops.xml", function(data) {
var xml = GXml.parse(data);
shop = xml.documentElement.getElementsByTagName("shop");
for (var i = 0; i < shop.length; i++) {
var name= shop[i].getElementsByTagName("name");
name = name[0].childNodes[0].nodeValue;
var address= shop[i].getElementsByTagName("address");
address = address[0].childNodes[0].nodeValue;
geocoder.getLocations(address, addToMap);}
}); }
function addToMap(response)
{
place = response.Placemark[0];
point = new GLatLng(place.Point.coordinates[1],place.Point.coordinates[0]);
function createMarker(point,address)
{
var marker = new GMarker(point);
GEvent.addListener(marker, "click", function()
{
map.openInfoWindowHtml(point, address);
});
return marker;
}
map.addOverlay(createMarker(point, response.name));
}
Use API v3 and in your marker setup set the tite of the marker to "name" then after adding the click listener you will be able to refer to the title of the clicked marker - if that is what you wanted.
//get your point and name whatever way you plan to do it
...
function createMarker(point,name){
var marker = new google.maps.Marker({
position: point,
map: map,
title: name,
}) ;
var content='Whatever info you want plus'+name;
var infowindow = new google.maps.InfoWindow({
content: content
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
return marker;
}
Please check the closures as I wrote it just now.
K
After some advice on how to clear markers on googlemaps, I have a map which I would like to have only one marker showing (basically the last marker clicked). I would like the user to be able to change thier mind and click multiple times, but not have confusing map of previous clicks etc.
I have tried the map.clearOverlay(); function, but it seems to permantly clear the whole map.
function initialize() {
if (GBrowserIsCompatible()) {
var map = new GMap2(document.getElementById("googlemap"));
map.setCenter(new GLatLng(50.401515,-4.866943), 8);
GEvent.addListener(map,"click", function(overlay,latlng) {
if (latlng) {
var myHtml = "" + latlng ;
split=myHtml.indexOf(",");
x=Math.round(myHtml.slice(1,split)*1000000)/1000000;
y=Math.round(myHtml.slice(split+1,myHtml.length-1)*1000000)/1000000;
document.collector.latitude.value=x;
document.collector.longitude.value=y;
lat="<br />Latitude: " + x;
lon="<br />Longitude: " + y;
latlon=""+lat+lon;
//map.openInfoWindow(latlng, latlon);
map.clearOverlay();
map.addOverlay(new GMarker(latlng));
}
});
map.addControl(new GLargeMapControl3D());
map.addControl(new GMapTypeControl());
}
}
Untested, but should do what you want - note that the setLatLng method of GMarker was introduced in API version 2.88:
function initialize() {
if (GBrowserIsCompatible()) {
var marker;
function showNewMarker(latlng) {
marker = new GMarker(latlng);
map.addOverlay(marker);
showMarker = updateExistingMarker;
}
function updateExistingMarker(latlng) {
marker.setLatLng(latlng);
}
var showMarker = showNewMarker;
var map = new GMap2(document.getElementById("googlemap"));
map.setCenter(new GLatLng(50.401515,-4.866943), 8);
GEvent.addListener(map,"click", function(overlay,latlng) {
if (latlng) {
var myHtml = "" + latlng ;
split=myHtml.indexOf(",");
x=Math.round(myHtml.slice(1,split)*1000000)/1000000;
y=Math.round(myHtml.slice(split+1,myHtml.length-1)*1000000)/1000000;
document.collector.latitude.value=x;
document.collector.longitude.value=y;
lat="<br />Latitude: " + x;
lon="<br />Longitude: " + y;
latlon=""+lat+lon;
//map.openInfoWindow(latlng, latlon);
map.clearOverlay();
showMarker(latlng);
}
});
map.addControl(new GLargeMapControl3D());
map.addControl(new GMapTypeControl());
}
}
It works by using a variable, showMarker, containing a reference to a function. This starts out pointing to a function, showNewMarker, which creates a marker, adds it to the map, and then changes showMarker to point to the function updateExistingMarker, which simply uses setLatLng to move the marker to a new position. This means that, on subsequent clicks, the existing marker will be moved to the location of the click.