user5563910
user5563910

Reputation:

Google Maps - How to call a function from a button in an infowindow?

I have a google map with a kml layer. The KML layer has a few markers on it. So far, i've managed to insert a button into the kml layer infowindow on click. I'm trying to add a marker at the place where it is clicked. I can do this just fine without kml layers. My click event calls an "addMarker" function which places the markers. I have a button in the infowindow which, when clicked, should add a marker at that point.

This is what i've done so far:

google.maps.event.addListener(layers[1], 'click', function(kmlEvent) {
var text = kmlEvent.featureData.name;
kmlEvent.featureData.infoWindowHtml += '<br/><button onclick="kmladd()" class="btn btn-success btn-sm">Add to Route</button>';
showInContentWindow(text);
});

function kmladd(){
addMarker(kmlEvent.latLng);
}

function showInContentWindow(text) {
var sidediv = document.getElementById('content-window');
}  

function addMarker(location) {

 var marker = new google.maps.Marker({
  map: map,
  position: location,
  draggable:true,
  icon: getMarkerIcon()
});
marker.identifier = 'waypoint_'+currentIndex;

 markers.push(marker);
}

I get an "Uncaught ReferenceError: kmladd is not defined" error. Is it possible to call a function on buttonclick of an infowindow?

Any assistance would be greatly appreciated.

Upvotes: 0

Views: 3083

Answers (1)

geocodezip
geocodezip

Reputation: 161334

The kmladd function needs to be in the global namespace to be used as an HTML onclick function.

proof of concept fiddle

code snippet:

var lastKmlEvent;
var map;

function initMap() {
  map = new google.maps.Map(document.getElementById('map'), {
    zoom: 11,
    center: {
      lat: 41.876,
      lng: -87.624
    }
  });

  var ctaLayer = new google.maps.KmlLayer({
    url: 'http://googlemaps.github.io/js-v2-samples/ggeoxml/cta.kml',
    map: map
  });
  google.maps.event.addListener(ctaLayer, 'click', function(kmlEvent) {
    lastKmlEvent = kmlEvent;
    var text = kmlEvent.featureData.name;
    kmlEvent.featureData.infoWindowHtml += '<br/><button onclick="kmladd()" class="btn btn-success btn-sm">Add to Route</button>';
  });
}

function addMarker(latLng) {
  var marker = new google.maps.Marker({
    position: latLng,
    title: latLng.toUrlValue(6),
    map: map
  });
}

function kmladd() {
  addMarker(lastKmlEvent.latLng);
}
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>

Upvotes: -1

Related Questions