Sadesh Kumar N
Sadesh Kumar N

Reputation: 2052

How to add a action for addDOMListener of Google Maps?

I just want to load the Google Maps based on the Mouseover event of different div element. For doing this I just used the following simple code. This code itself not working, can someone tell me what mistake I have made?

<script type="text/javascript">

  function initialize() {
    var mapDiv = document.getElementById('map-canvas');
    var map = new google.maps.Map(mapDiv, {
      center: new google.maps.LatLng(40.740, -74.18),
      zoom: 12,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });

    var content = '<strong>A info window!</strong><br/>That is bound to a marker';

    var infowindow = new google.maps.InfoWindow({
      content: content
    });

    var marker = new google.maps.Marker({
      map: map,
      position: map.getCenter(),
      draggable: true
    });

    infowindow.open(map, marker);
  }

  google.maps.event.addDomListener($("#showmap"), 'mouseover', function(){ alert("Hi");});
</script>


<div id='showmap'>
  Show Map
</div>
<div id="map-canvas" style="width: 500px; height: 400px"></div>

Above simple alert function itself not called for this simple code.

Upvotes: 0

Views: 12265

Answers (2)

Sadesh Kumar N
Sadesh Kumar N

Reputation: 2052

I just tried using this and this also worked.

Java Script Code:

  function initialize(lat,longit,content) {
    var mapDiv = document.getElementById('map-canvas');
    var map = new google.maps.Map(mapDiv, {
      center: new google.maps.LatLng(lat, longit),
      zoom: 14,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });


    var infowindow = new google.maps.InfoWindow({
      content: content
    });

    var marker = new google.maps.Marker({
      map: map,
      position: map.getCenter(),
      draggable: false
    });

    infowindow.open(map, marker);
  }

Html Code:

 <div id='showmap' onclick="initialize(1.37422,103.945,'<h2>Tampines</h2>')">
  Show Map
</div>

I just tried using an idea from java, can we try a method call from the onclick and check whether it is working and to my surprise it worked.

Upvotes: 0

Tina CG Hoehr
Tina CG Hoehr

Reputation: 6779

The selector returns the jQuery object and the needed element can be accessed directly from the element array with a [0] . Also, make it "addDomListenerOnce", only need to initialize once.

$("#showmap")[0]

see a demo

google.maps.event.addDomListenerOnce($("#showmap")[0], 'mouseover', 
                                 function(){ initialize(); });

Upvotes: 4

Related Questions