Search code examples
javascriptjquerycssgoogle-mapsgmaps4rails

Uncaught No element defined?


I'm using gmaps.js. I'm getting the Uncaught ReferenceError: gmaps.js:205 Uncaught No element defined. The following screenshot shows how Chrome reports the error in the gmaps Javascripts:

But i have it true in jsfiddle, but same code on my localhost (XAMPP) problem.

enter image description here

    var map = new GMaps({
    el: '#map',
    lat: -12.043333,
    lng: -77.028333,
    click: function(event) {
        map.removeMarkers();
        var lat = event.latLng.lat();
        var lng = event.latLng.lng();
        alert(lat + ', ' + lng);
        map.addMarker({
            lat: lat,
            lng: lng,
            draggable: true,
        });
    }
});
$('select,input').change(function() {
    var searchString = [$('select.Country').val(), $('select.Cities').val(), $('input#SearchDistrict').val()].join(', ');
    alert(searchString);
    GMaps.geocode({
        address: searchString.trim(),
        callback: function(results, status) {
            if (status == 'OK') {
                var latlng = results[0].geometry.location;
                map.setCenter(latlng.lat(), latlng.lng());
                map.addMarker({
                    lat: latlng.lat(),
                    lng: latlng.lng()
                });
            }
        }
    });

});
#map {
      width: 400px;
      height: 400px;
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://maps.google.com/maps/api/js?sensor=true"></script>
  <script src="https://hpneo.github.io/gmaps/gmaps.js"></script>
<form>
    Country:
    <select class="Country">
        <option value="" selected="selected"></option>
        <option value="United States">United States</option>
    </select>
    Cities:
    <select class="Cities">
        <option value="" selected="selected"></option>
        <option value="New York">New York</option>
    </select>
    District:
    <input type="text" id="SearchDistrict">
</form>
        <div class="popin">
          <div id="map"></div>
        </div>

I am not able to fix this, so I need your support.What do i do?


Solution

  • I have tested the script and it works fine. The error you see happens only if <div id="map"/> does not exists in moment you create the map.

    What you should do is to call the map creation script after you insert the map container into DOM tree.