I have an issue in my google api code. The problem is I used geocoding in bootstrap modal, on first clik when i filled the inputs I have information in console: Cannot read property of null. Here is sample of my code:
var location1;
var location2;
function licz() {
var geocoder = new google.maps.Geocoder();
if (geocoder) {
geocoder.geocode({ 'address': document.getElementById('txtMiasto1').value }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
location1 = results[0].geometry.location;
console.log(location1);
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
geocoder.geocode({ 'address': document.getElementById('txtMiasto2').value }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
location2 = results[0].geometry.location;
console.log(location2);
} else {
alert("Geocode was not successful for the following reason: " + status);
latlng = new google.maps.LatLng((location1.lat() + location2.lat()) / 2, (location1.lng() + location2.lng()) / 2);
var mapOptions = {
center: latlng,
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
directionsService = new google.maps.DirectionsService();
directionsDisplay = new google.maps.DirectionsRenderer(
{
suppressMarkers: true,
suppressInfoWindows: true
});
directionsDisplay.setMap(map);
var request = {
origin: location1,
destination: location2,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
distance = response.routes[0].legs[0].distance.text;
document.getElementById("txtDistance").value = distance;
}
});
var marker1 = new google.maps.Marker({
map: map,
position: location1,
title: "Start"
});
var marker2 = new google.maps.Marker({
map: map,
position: location2,
title: "Koniec"
});
}
var geocoder = new google.maps.Geocoder();
if (geocoder) {
geocoder.geocode({ 'address': document.getElementById('txtMiasto1').value }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
location1 = results[0].geometry.location;
console.log(location1);
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
geocoder.geocode({ 'address': document.getElementById('txtMiasto2').value }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
location2 = results[0].geometry.location;
console.log(location2);
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
The function licz() is handled OnClick in button on modal like this:
<button type="button" runat="server" id="btnLicz" class="btn btn-info" onclick="licz();">Calculate</button>
When i Click again the problem solved.
Could someone of You tell me what I'm doing wrong?
Thanks for help!