Getting Error Cannot set property 'innerText' of null - javascript

I have a scenario of adding text to html element using id. But I am getting error.
First the html gets dynamically loaded then I am adding add variable to the html element using id detail
geocoder.geocode({
'location': temp1
}, function(results, status) {
if (status === 'OK') {
if (results[1]) {
add = results[1].formatted_address;
var marker0 = createMarker({
position: temp1,
map: map,
}, '<h1>Details</h1><p id="detail"></p>');
} else {
window.alert('No results found');
}
} else {
window.alert('Geocoder failed due to: ' + status);
}
});
var geocoder = new google.maps.Geocoder;
var infoWindow = new google.maps.InfoWindow();
var add;
/*
* marker creater function (acts as a closure for html parameter)
*/
function createMarker(options, html) {
var marker = new google.maps.Marker(options);
if (html) {
google.maps.event.addListener(marker, "click", function() {
infoWindow.setContent(html);
console.log(add);
document.getElementById('detail').innerText = add;
infoWindow.open(options.map, this);
});
}
return marker;
}
Html is getting appended but document.getElementById('detail') is giving a null value.
Any help is appreciated.

Related

Mark multiple locations in Google Map

I am using Google map api v3 to plot markers of location array. My script is
function OnSuccess(response) {
var markers = response.d.split('^^');
var latlng = new google.maps.LatLng(51.474634, -0.195791);
var mapOptions1 = {
zoom: 14,
center: latlng
}
var geocoder = new google.maps.Geocoder();
var infoWindow = new google.maps.InfoWindow();
var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions1);
for (i = 0; i < markers.length; i++) {
var data = markers[i];
geocoder.geocode({ 'address': data }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
title: data
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
(function (marker, data) {
// Attaching a click event to the current marker
google.maps.event.addListener(marker, "click", function (e) {
infoWindow.setContent(data);
infoWindow.open(map, marker);
});
})(marker, data);
}
where markers variable is bringing proper data, my test data is array of 5 elements
The Game Larder, 24 The Parade, Claygate, Surrey,KT10 0NU
24 The Parade, Claygate, Esher, Surrey KT10 0NU
Card Collection, 14 The Parade, Claygate, ESHER, KT10 0NU
16A The Parade, Claygate, ESHER, KT10 0NU
and same is coming into array markers however it is plotting only two markers. What could be wrong here
Solution
I was entering locations which are very close to each other e.g 1 and 2 point which gives same latlong hence mark as one place. I found latlong here. Thanks for answers btw :)
In page.aspx. insert tag <div id="map-canvas" ></div>
view source page.aspx and insert script into it>
var lis_marker = new Array();
for (i = 0; i < markers.length; i++) {
var data = markers[i];
geocoder.geocode({ 'address': data }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
lis_marker[i] = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
title: data
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
there are difference with your code:
1: var lis_marker = new Array();
2: lis_marker[i] = new google.maps.Marker({...});

Google Maps infowindow don't work on marker click

I'm using Google Maps API v3 geocoding service. The geocoding part works fine. I type a zip code in a textbox and then hit the submit button. Then it shows a blue marker at the place which I typed in the textbox. And then it loads places in a radius of 20km and display these with a red marker. That all works fine. But then I got some problems with the infowindow.
If I click on a marker (red or blue) it happens nothing. And I just can't figure it out. I use this code for infowindow:
$.ajax({
url: 'data.php',
type: 'POST',
data: {xmldata: jqXHR.responseText},
success: function(locations, textStatus, jqXHR){
var split = locations.split(",");
var checkForDouble = split.filter(function(elem, pos) {
return split.indexOf(elem) == pos;
});
for(var i = 0; i < split.length; i++){
geocoder.geocode(
{'address': checkForDouble[i]},
function(results, status){
if(results != null){
marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
}
}
);
var infocontent = checkForDouble[i];
var infowindow = new google.maps.InfoWindow();
google.maps.event.addListener(marker, 'click', (function(marker, infocontent) {
return function(){
infowindow.setContent(infocontent);
infowindow.open(map, marker);
}
})(marker, infocontent));
}
}
Can someone give me a hint where I made the error?
You need function closure on your geocoder call also.
var infowindow = new google.maps.InfoWindow();
function createMarker(address)
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
var infocontent = address;
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(infocontent);
infowindow.open(map, marker);
});
return marker;
}
function geocodeAddress(address) {
geocoder.geocode(
{'address': address,
function(results, status){
if((results != null) && (status == google.maps.GeocoderStatus.OK)) {
var marker = createMarker(address);
} else alert("geocode failed on "+address+", status="+status);
}
);
}
$.ajax({
url: 'data.php',
type: 'POST',
data: {xmldata: jqXHR.responseText},
success: function(locations, textStatus, jqXHR){
var split = locations.split(",");
var checkForDouble = split.filter(function(elem, pos) {
return split.indexOf(elem) == pos;
});
for(var i = 0; i < split.length; i++){
geocodeAddress(checkForDouble[i]);
}
}
you have to use closure around your listener because it will use your parameter in future. you have to pass data to anonymous function.
With this code you can get your structure.
$.ajax({
url: 'data.php',
type: 'POST',
data: {xmldata: jqXHR.responseText},
success: function(locations, textStatus, jqXHR){
var split = locations.split(",");
var checkForDouble = split.filter(function(elem, pos) {
return split.indexOf(elem) == pos;
});
for(var i = 0; i < split.length; i++){
geocoder.geocode(
{'address': checkForDouble[i]},
function(results, status){
if(results != null){
marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
}
}
);
(function (infocontent){
google.maps.event.addListener(marker, 'click', function() {
infowindow = new google.maps.InfoWindow();
infowindow.setContent(infocontent);
infowindow.open(map, marker);
}
});
})(checkForDouble[i])
}
}

Google Places and ZERO_RESULTS

I've been working on this very simple Google Places search and I cannot get anything but a ZERO_RESULTS. It makes no sense to me at this point as my map is working and displays markers from my database within a separate AJAX function. I've logged my objects and variables and all seem to be just fine.
Why does the success callback go right to my else statement with ZERO_RESULTS?
$( "#submit3" ).click(function(e) {
e.preventDefault();
findPlaces();
$('#results').text("Triggah3!");
});
function findPlaces() {
var lat = document.getElementById("latitude").value;
var lng = document.getElementById("longitude").value;
var cur_location = new google.maps.LatLng(lat, lng);
// prepare request to Places
var request = {
location: cur_location,
radius: 50000,
types: 'bank'
};
// send request
service = new google.maps.places.PlacesService(map);
service.search(request, createMarkers);
}
// create markers (from 'findPlaces' function)
function createMarkers(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) { //ZERO_RESULTS
// if we have found something - clear map (overlays)
clearOverlays();
// and create new markers by search result
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
} else if (status == google.maps.places.PlacesServiceStatus.ZERO_RESULTS) {
alert('Sorry, nothing is found');
}
}
// create single marker function
function createMarker(obj) {
// prepare new Marker object
var mark = new google.maps.Marker({
position: obj.geometry.location,
map: map,
title: obj.name
});
markers.push(mark);
// prepare info window
var infowindow = new google.maps.InfoWindow({
content: '<img src="' + obj.icon + '" /><font style="color:#000;">' + obj.name +
'<br />Rating: ' + obj.rating + '<br />Vicinity: ' + obj.vicinity + '</font>'
});
// add event handler to current marker
google.maps.event.addListener(mark, 'click', function() {
clearInfos();
infowindow.open(map,mark);
});
infos.push(infowindow);
}
types is expected to be an array.
Use:
types: ['bank']

Javascript Equating Variable .value

This is the code I'm working from: http://jsfiddle.net/9B84H/26/
function autosuggest() {
var input = document.getElementById('location');
var options = {types: [],};
var autocomplete = new google.maps.places.Autocomplete(input, options);
}
function getLatLng() {
var geocoder = new google.maps.Geocoder();
var address = document.getElementById('location').value;
geocoder.geocode({
'address': address
}, function (results, status) {
if (status === google.maps.GeocoderStatus.OK) {
$('#lat').val(results[0].geometry.location.lat());
$('#lng').val(results[0].geometry.location.lng());
} else {
alert("Geocode failed: " + status);
}
});
}
There are two variables which are pretty much the same​:
var address = document.getElementById('location').value;
var input = document.getElementById('location');
Is there any opportunity to combine this into one line as a global variable?
You could use your anonymous self invoking function or just use the dom-ready method in jQuery to wrap your code (dom-ready seems like a better idea if you don´t put your JS code at the bottom of the page).
I did an example removing the onclick, onfocus attribute on your input and put them in the javascript section: http://jsfiddle.net/9B84H/27/
$(function() {
var location = document.getElementById('location');
var getLatLng = function() {
var geocoder = new google.maps.Geocoder();
var address = location.value;
geocoder.geocode({
'address': address
}, function (results, status) {
if (status === google.maps.GeocoderStatus.OK) {
$('#lat').val(results[0].geometry.location.lat());
$('#lng').val(results[0].geometry.location.lng());
alert("Geocode success");
} else {
alert("Geocode failed: " + status);
}
});
};
var autosuggest = function() {
var options = {types: []};
var autocomplete = new google.maps.places.Autocomplete(location, options);
};
$("#location").on("focus", autosuggest);
$(":button[name='Geocode']").on("click", getLatLng);
});
you now have a local variable named location that reference the #location element in your document.

Javascript Loop - 2nd variable Not Displaying

Here is the code:
<script type="text/javascript">
var offender_locations = [
["10010", "xxxxx", 3],
["10001", "xxxxx", 2],
["10002", "zzzzz", 1]
];
for (i = 0; i < offender_locations.length; i++) {
var address = offender_locations[i][0];
var icon_img = offender_locations[i][1];
}
</script>
This is the output:
1) 10010 - zzzzz
2) 10001 - zzzzz
3) 10002 - zzzzz
AS you can see var address outputs the correct value, but *var icon_img* does always repeat the same value.
I am a Javascript beginner and I have tried all ways I can think of but I still get the same results.
P.S. I have pasted the full script here :
<script type="text/javascript">
var offender_locations = [
["10010", "offender_icon.png", 3],
["10001", "offender_icon.png", 2],
["10002", "visitor_icon.png", 1]
];
var myOptions = {
zoom: 10,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map"), myOptions);
var latlng = new google.maps.LatLng(0, 0);
for (i = 0; i < offender_locations.length; i++) {
var infowindow = new google.maps.InfoWindow();
var geocoder_map = new google.maps.Geocoder();
var address = offender_locations[i][0];
var icon_img = offender_locations[i][1];
geocoder_map.geocode({
'address': address
}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: map.getCenter(),
icon: icon_img
});
google.maps.event.addListener(marker, 'click', (function (marker, i) {
return function () {
infowindow.setContent(offender_locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
} else {
alert("The requested offender is not mappable !")
};
});
}
</script>
The markers in this script are all # the correct postal code, but they all show the same icon (visitor_icon.png) !
The problem is that you are creating a function in a loop. JavaScript has only function scope, not block scope. I.e. variables you create in a loop exist only once in the whole function, just the values changes per iteration.
At the time icon_img is evaluated (in the callback passed to geocode), the outer for loop already finished and icon_img has the value of the last iteration. It works for address because it is evaluated inside the loop, not later.
You have to 'capture' the current value of icon_img and you can do so by using an immediate function:
for (i = 0; i < offender_locations.length; i++) {
var infowindow = new google.maps.InfoWindow(),
geocoder_map = new google.maps.Geocoder(),
address = offender_locations[i][0],
icon_img = offender_locations[i][1];
(function(addr, img) { // <-- immediate function call
geocoder_map.geocode({'address': addr}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: map.getCenter(),
icon: img
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(addr);
infowindow.open(map, marker);
});
} else {
alert("The requested offender is not mappable !");
}
});
}(address, icon_img)); // <-- immediate function call
}
Maybe you hav to do this for even more variables... not sure.

Categories