I try to insert a marker with a form in InfoWindow, but with the first click into the map I got this error:
Uncaught TypeError: Cannot set property 'value' of null
It is because getElementById
is NULL
, when I click a second time it is matching. I tried some hours but didn't get it :-/
My code (part of):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<script src="https://maps.googleapis.com/maps/api/js"></script>
<script>
var map;
var marker;
function initJsMap() {
var vienna = new google.maps.LatLng(48.2134567, 16.3789012);
var mapOptions = {
position: vienna,
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map-canvas"),mapOptions);
google.maps.event.addListener(map, 'dblclick', function(event) {
placeMarker(event.latLng);
});
}
function placeMarker(location) {
if (marker) {
marker.setPosition(location);
} else {
var form = '<div id="form_canvasform">' +
'<form method="POST" action="/addmap" name="form_canvas">' +
'<div style="display:none;">' +
'<input id="csrf_token" name="csrf_token" type="hidden" value="foo">' +
'<input id="latitude" name="latitude" type="hidden" value="">' +
'<input id="longitude" name="longitude" type="hidden" value=""></div>' +
'<label for="link">link</label> <input id="link" name="link" type="text" value="">' +
'<input type="submit" value="Go!">' +
'</form>' +
'</div>';
infowindow = new google.maps.InfoWindow({
content: form
});
marker = new google.maps.Marker({
position: location,
map: map,
draggable: true
});
infowindow.open(map, marker);
marker.addListener('click', function() {
infowindow.open(map, marker);
});
}
console.log("Latitude: " + location.lat());
console.log("Longitude: " + location.lng());
console.log(form);
document.getElementById('latitude').value = location.lat();
document.getElementById('longitude').value = location.lng();
}
</script>
</head>
<body onload="initJsMap()">
<div id="map-canvas" style="width:50%; height:600px;"></div>
</body>
</html>
The form content is generated by jinja2 templating engine (with flask). With the console.log()
I get the correct values.
[EDIT]:
This is the jinja code who generate the form:
var form = '<div id="form_canvasform">' +
'<form method="POST" action="{{ request.path }}" name="form_canvas">' +
'{{ form.hidden_tag() }}' +
'{{ form.link.label }} {{ form.link }}' +
'<br/>' +
'<input type="submit" value="Go!">' +
'</form>' +
'</div>';