Google maps listener event acts like a click even though it is a mouseover

I am adding these two google.maps.event.addListener events

google.maps.event.addListener(markerAcademicCenter, "mouseover", function (e) {
   markerIconAcademicCenter.url = 'MapIcons/Circle32.png'
});
google.maps.event.addListener(markerAcademicCenter, "mouseout", function (e) {
   markerIconAcademicCenter.url = 'MapIcons/Circle64.png'
});

below this marker that already has a click event.

google.maps.event.addListener(markerAcademicCenter, "click", function (e) {
   $(".campusMapInfoPanel > div").appendTo($(".InfoStorageDiv"));
   $(".InfoPanelAcademicCenter").appendTo($(".campusMapInfoPanel"));
   this.setZIndex(google.maps.Marker.MAX_ZINDEX + 1);
   setZoomWhenMarkerClicked();
   CampusMap.setCenter(markerAcademicCenter.getPosition());
});

The markerIconAcademicCenter.url is already set to Circle64 above these events. I expect the page to load with the larger circle — 64x64 — the switch back and forth as I hover and leave the marker area.

I'm having two problems with this

  1. Nothing happens when I mouseover the marker, but it does happen when I click. On the initial click after the page loads, the map zooms and centers on the building and the marker image resizes. If I click on the building again, nothing else happens, but:
  2. if I click on a menu link that triggers the click event, function buildingFocus(markerName) {google.maps.event.trigger(markerName, "click");} that function resets the icon as if it were the mouseout event.

To test this unexpected behavior further, I commented out each event one at a time. To clarify that something was actually happening, I first changed the initial image to clear.png.

When I took out the mouseover event, the image did not change when I clicked either the building event or the menu link as my first click after the page loaded. Before I removed the mouseover event, clicking on the menu as my second click after page load changed the icon to the mouseout image, but now clicking on the building causes this.

When I took out the mouseout event, clicking on the building as the first click made the icon change to the mouseover image, and clicking again on either area did nothing further. If I clicked on the menu link as the first or future clicks the image didn't change, but it did as soon as I clicked on the building.

When I took the click event out, the image never changed. By itself, the click event works as expected with both locations.

Answers:

Answer

The icon of a marker is not an MVCObject, the API will not observe changes of the icon-properties.

You must modify the url of the icon and then call setIcon to apply the changes:

google.maps.event.addListener(markerAcademicCenter, "mouseover", function (e) {
  var icon = this.getIcon();
  icon.url =  'url/to/icon';
  this.setIcon(icon);
});

But I wouldn't suggest it, when you use the icon for multiple markers changing the url(or other properties) will affect the original icon markerIconAcademicCenter (markers use a reference to the original object). You better create a copy with a modified url:

google.maps.event.addListener(markerAcademicCenter, "mouseover", function (e) {
  var icon = this.getIcon(),copy={};
     for(var k in icon){
      copy[k]=icon[k];
     }
  copy.url=  'url/to/icon';     
  this.setIcon(copy);
});
Answer

Try using this :

google.maps.event.addListener(markerAcademicCenter, "mouseover", function (e) {
   markerIconAcademicCenter.setIcon('url to icon');
});

instead of code below :

google.maps.event.addListener(markerAcademicCenter, "mouseover", function (e) {
   markerIconAcademicCenter.url = 'MapIcons/Circle32.png'
});

This will sort out your problem of icon size change on mouseover and mouseout problem.

Answer

You can check the code below, so that you will be clear what I mean to say :

<!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>Google Maps JavaScript API v3 Example: Map Simple</title>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?libraries=places"></script>
<script type="text/javascript">

  var map, places, iw;
  var markers = [];
  var autocomplete;
  var options = {
        //types: ['(cities)'],
        //componentRestrictions: {country: 'us'}
    };
  var geocoder = new google.maps.Geocoder();
  function initialize() {
    var myLatlng = new google.maps.LatLng(37.783259, -122.402708);
    var myOptions = {
      zoom: 12,
      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);
    autocomplete = new google.maps.places.Autocomplete(document.getElementById('autocomplete'), options);
    google.maps.event.addListener(autocomplete, 'place_changed', function() {
      showSelectedPlace();
    });
  }

  function tilesLoaded() {
    google.maps.event.clearListeners(map, 'tilesloaded');
    google.maps.event.addListener(map, 'zoom_changed', search);
    google.maps.event.addListener(map, 'dragend', search);
    search();
  }

  function showSelectedPlace() {
    clearResults();
    clearMarkers();
    var place = autocomplete.getPlace();
    map.panTo(place.geometry.location);
    markers[0] = new google.maps.Marker({
      position: place.geometry.location,
      map: map
    });
    iw = new google.maps.InfoWindow({
      content: getIWContent(place)
    });
    iw.open(map, markers[0]);
    search();
  }

  function search() {
    var type;
    for (var i = 0; i < document.controls.type.length; i++) {
      if (document.controls.type[i].checked) {
        type = document.controls.type[i].value;
      }
    }

    autocomplete.setBounds(map.getBounds());

    var search = {
      bounds: map.getBounds()
    };

    if (type != 'establishment') {
      search.types = [ type ];
    }

    places.search(search, function(results, status) {
      if (status == google.maps.places.PlacesServiceStatus.OK) {
        clearResults();
        clearMarkers();
        for (var i = 0; i < 9; i++) {
          markers[i] = new google.maps.Marker({
            position: results[i].geometry.location,
            animation: google.maps.Animation.DROP
          });

          google.maps.event.addListener(markers[i], 'mouseover', animate(i));
          google.maps.event.addListener(markers[i], 'mouseout', reanimate(i));
          google.maps.event.addListener(markers[i], 'click', getDetails(results[i], i));
          setTimeout(dropMarker(i), i * 100);
          //addResult(results[i], i);
          mygetDetails(results[i], i);
        }
      }
    })
  }

  function clearMarkers() {
    for (var i = 0; i < markers.length; i++) {
      if (markers[i]) {
        markers[i].setMap(null);
        markers[i] == null;
      }
    }
  }

  function dropMarker(i) {
    return function() {
      markers[i].setMap(map);
    }
  }

  //Function to animate markers on there hover
    function animate(locationCount){
        return function(){ 
            markers[locationCount].setIcon('https://mts.googleapis.com/vt/icon/name=icons/spotlight/spotlight-poi.png&scale=2');
            $("#addressSpan"+locationCount).css('font-weight', '700');
            $("#addressSpan"+locationCount).css('color', '#ff0000');
        }
    }

    //Function to remove animation of markers on there hover
    function reanimate(locationCount){ 
        return function(){ 
            markers[locationCount].setIcon('https://mts.googleapis.com/vt/icon/name=icons/spotlight/spotlight-poi.png&scale=1');
            $("#addressSpan"+locationCount).css('font-weight', '');
            $("#addressSpan"+locationCount).css('color', '');
        }
    }

  function addResult(result, i) {

    if(i<=9){
        var results = document.getElementById("results");
        var tr = document.createElement('tr');
        tr.style.backgroundColor = (i% 2 == 0 ? '#F0F0F0' : '#FFFFFF');
        tr.click = function() {
        google.maps.event.trigger(markers[i], 'click');
        };

        var iconTd = document.createElement('td');
        var nameTd = document.createElement('td');
        var addressTd = document.createElement('td');
        var icon = document.createElement('img');
        icon.src = result.icon;
        icon.setAttribute("class", "placeIcon");
        icon.setAttribute("className", "placeIcon");
        var name = document.createTextNode(result.name);
        var address = document.createTextNode(result.formatted_address);

        iconTd.appendChild(icon);
        nameTd.appendChild(name);
        addressTd.appendChild(address);
        tr.appendChild(iconTd);
        tr.appendChild(nameTd);
        tr.appendChild(addressTd);
        results.appendChild(tr);
    }
  }

  function clearResults() {
    var results = document.getElementById("results");
    while (results.childNodes[0]) {
      results.removeChild(results.childNodes[0]);
    }
  }

  function clearResults1() {
    var results = document.getElementById("results1");
    while (results.childNodes[0]) {
      results.removeChild(results.childNodes[0]);
    }
  }

  function getDetails(result, i) {
    return function() {
      places.getDetails({
          reference: result.reference
      }, showInfoWindow(i));
    }
  }

  function mygetDetails(result, i) {
    return places.getDetails({
          reference: result.reference
      }, function(place, status){
            if (status == google.maps.places.PlacesServiceStatus.OK) {
                addResult(place, 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><tr><td>';
    content += '<img class="placeIcon" src="' + place.icon + '"/></td>';
    content += '<td><b><a href="' + place.url + '">' + place.name + '</a></b>';
    content += '</td></tr></table>';
    return content;
  }

  $(function(){
        $("#autocomplete").keyup(function(){
            clearResults1();
            geocoder.geocode({"address": $(this).val()}, function(data, status) {
                if (status == google.maps.GeocoderStatus.OK) {
                    $.each(data, function(int_index,value) {
                        var results = document.getElementById("results1");
                        var tr = document.createElement('tr');
                        tr.style.backgroundColor = (int_index% 2 == 0 ? '#F0F0F0' : '#FFFFFF');
                        var nameTd = document.createElement('td');
                        var name = document.createTextNode(value.formatted_address);
                        nameTd.appendChild(name);
                        tr.appendChild(nameTd);
                        results.appendChild(tr);
                    });
                }
            });
        });
    });
</script>
<style>
body {
  font-family: sans-serif;
}
#map_canvas {
  position: absolute;
  width: 399px;
  height: 399px;
  top: 25px;
  left: 0px;
  border: 1px solid grey;
}
#listing {
  position: absolute;
  width: 200px;
  height: 360px;
  overflow: auto;
  left: 401px;
  top: 65px;
  cursor: pointer;
}
#listing1 {
  position: absolute;
  width: 200px;
  height: 360px;
  overflow: auto;
  left: 601px;
  top: 65px;
  cursor: pointer;
}
#controls {
  width: 200px;
  position: absolute;
  top: 0px;
  left: 400px;
  height: 60px;
  padding: 5px;
  font-size: 12px;
}
.placeIcon {
  width: 16px;
  height: 16px;
  margin: 2px;
}
#resultsTable, #resultsTable1{
  font-size: 10px;
  border-collapse: collapse;
}
#locationField {
  width: 400px;
  height: 25px;
  top: 0px;
  left: 0px;
  position: absolute;
}
#autocomplete {
  width: 400px;
}
</style>
</head>
<body style="margin:0px; padding:0px;" onLoad="initialize()">
  <div id="locationField">
    <input id="autocomplete" type="text" />
  </div>
  <div id="controls">
    <form name="controls">
    <input type="radio" name="type" value="establishment" onClick="search()" checked="checked"/>All<br/>
    <input type="radio" name="type" value="restaurant" onClick="search()" />Restaurants<br/>
    <input type="radio" name="type" value="lodging" onClick="search()" />Lodging
    </form>
  </div>
  <div id="map_canvas"></div>
  <div id="listing"><table id="resultsTable"><tr><td><h3>Suggested<br>Locations</h3></td></tr><tbody id="results"></tbody></table></div>
  <div id="listing1"><table id="resultsTable1"><tr><td><h3>Suggested<br>Address</h3></td></tr><tbody id="results1"></tbody></table></div>
</body>
</html>

This is a working example.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.