I am using google maps, And in a textfield you can type a place and then you will see a marker on the google maps with the coordinates. You can also move the maker and then the coordinates in the info box will be updated. But how to update also the place name in the textfield? Thank you.
This is the jquery script:
var map;
function initMap() {
var geocoder = new google.maps.Geocoder();
var startaddress = $('#form_inp19').val();
geocoder.geocode({ 'address': startaddress }, function (results, status) {
if (status === google.maps.GeocoderStatus.OK) {
startLocationMap = results[0].geometry.location;
map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center: startLocationMap
});
geocoder = new google.maps.Geocoder();
document.getElementById('submit').addEventListener('click', function () {
geocodeAddress(geocoder, map);
});
} else {
alert('Place doesnt exist on the map: ' + status);
}
if (typeof google.maps == 'undefined') {
/* custom functions to alert the user to the error */
return 0;
}
});
}//end function initMap
$(document).ready(function () {
if (typeof google.map == 'undefined') {
return 0;
}
map = new google.maps.Map(document.getElementById('map'),
mapOptions);
});
function toggleBounce() {
if (marker.getAnimation() !== null) {
marker.setAnimation(null);
} else {
marker.setAnimation(google.maps.Animation.BOUNCE);
}
}
var marker;
var infowindow;
function geocodeAddress(geocoder, resultsMap) {
if (typeof infowindow != 'undefined') {
infowindow.close();
}
if (typeof marker != 'undefined') {
marker.setMap(null);
}
var address = document.getElementById('address').value;
geocoder.geocode({ 'address': address }, function (results, status) {
if (status === google.maps.GeocoderStatus.OK) {
resultsMap.setCenter(results[0].geometry.location);
marker = new google.maps.Marker({
map: resultsMap,
draggable: true,
animation: google.maps.Animation.DROP,
position: results[0].geometry.location,
title: "Drag me!"
});
} else {
alert('Place doesnt exist on the map: ' + status);
}
infowindow = new google.maps.InfoWindow({
content: '<p>Marker Location:'
+ 'lat: ' + marker.getPosition().lat().toFixed(6)
+ ', '
+ 'lng: ' + marker.getPosition().lng().toFixed(6)
+ '</p>'
});
$(".geolocation_lat ").val(marker.getPosition().lat().toFixed(6)) //= marker.getPosition().lat().toFixed(6);
$(".geolocation_long ").val(marker.getPosition().lng().toFixed(6))
google.maps.event.addListener(marker, 'dragend', function (event) {
if (typeof infowindow != 'undefined') {
infowindow.close();
}
infowindow = new google.maps.InfoWindow({
content: '<p>Marker Location:'
+ 'lat: ' + event.latLng.lat().toFixed(6)
+ ', '
+ 'lng: ' + event.latLng.lng().toFixed(6)
+ '</p>'
});
$(".geolocation_lat ").val(event.latLng.lat().toFixed(6)); //= marker.getPosition().lat().toFixed(6);
$(".geolocation_long ").val(event.latLng.lng().toFixed(6));
infowindow.open(map, marker);
});
infowindow.open(map, marker);
google.maps.event.addListener(marker, 'click', function (event) {
if (typeof infowindow != 'undefined') {
infowindow.open(map, marker);
}
});
});
}
I have it now like this:
var map;
function initMap() {
var geocoder = new google.maps.Geocoder();
var startaddress = $('#form_inp19').val();
geocoder.geocode({ 'address': startaddress }, function (results, status) {
if (status === google.maps.GeocoderStatus.OK) {
startLocationMap = results[0].geometry.location;
map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center: startLocationMap
});
geocoder = new google.maps.Geocoder();
document.getElementById('submit').addEventListener('click', function () {
geocodeAddress(geocoder, map);
});
} else {
alert('Place doesnt exist on the map: ' + status);
}
if (typeof google.maps == 'undefined') {
/* custom functions to alert the user to the error */
return 0;
}
});
}//end function initMap
$(document).ready(function () {
if (typeof google.map == 'undefined') {
return 0;
}
map = new google.maps.Map(document.getElementById('map'),
mapOptions);
});
function toggleBounce() {
if (marker.getAnimation() !== null) {
marker.setAnimation(null);
} else {
marker.setAnimation(google.maps.Animation.BOUNCE);
}
}
var marker;
var infowindow;
//Added
function geocodePosition(pos) {
geocoder.geocode({
latLng: pos
}, function (responses) {
if (responses && responses.length > 0) {
document.getElementById('address') = responses[0].formatted_address;
} else {
document.getElementById('address') = 'Cannot determine address at this location.';
}
});
}
function geocodeAddress(geocoder, resultsMap) {
if (typeof infowindow != 'undefined') {
infowindow.close();
}
if (typeof marker != 'undefined') {
marker.setMap(null);
}
var address = document.getElementById('address').value;
geocoder.geocode({ 'address': address }, function (results, status) {
if (status === google.maps.GeocoderStatus.OK) {
resultsMap.setCenter(results[0].geometry.location);
marker = new google.maps.Marker({
map: resultsMap,
draggable: true,
animation: google.maps.Animation.DROP,
position: results[0].geometry.location,
title: "Drag me!"
});
} else {
alert('Place doesnt exist on the map: ' + status);
}
infowindow = new google.maps.InfoWindow({
content: '<p>Marker Location:'
+ 'lat: ' + marker.getPosition().lat().toFixed(6)
+ ', '
+ 'lng: ' + marker.getPosition().lng().toFixed(6)
+ '</p>'
});
$(".geolocation_lat ").val(marker.getPosition().lat().toFixed(6)) //= marker.getPosition().lat().toFixed(6);
$(".geolocation_long ").val(marker.getPosition().lng().toFixed(6))
google.maps.event.addListener(marker, 'dragend', function (event) {
geocodePosition(marker.getPosition());
if (typeof infowindow != 'undefined') {
infowindow.close();
}
infowindow = new google.maps.InfoWindow({
content: '<p>Marker Location:'
+ 'lat: ' + event.latLng.lat().toFixed(6)
+ ', '
+ 'lng: ' + event.latLng.lng().toFixed(6)
+ '</p>'
});
$(".geolocation_lat ").val(event.latLng.lat().toFixed(6)); //= marker.getPosition().lat().toFixed(6);
$(".geolocation_long ").val(event.latLng.lng().toFixed(6));
infowindow.open(map, marker);
});
infowindow.open(map, marker);
google.maps.event.addListener(marker, 'click', function (event) {
if (typeof infowindow != 'undefined') {
infowindow.open(map, marker);
}
});
});
}
But I get the error:
'geocoder' is undefined
I only get this error:
Cannot assign to a function result
document.getElementById('address') = responses[0].formatted_address;
I see the address: responses[0].formatted_address "Belle van Zuylenlaan 23-24, 2642 Pijnacker, Nederland"
But how to get only the place name in the textfield?
Thank you
In your dragend listener,
google.maps.event.addListener(marker, 'dragend', function() {
geocodePosition(marker.getPosition());
});
and
function geocodePosition(pos) {
geocoder = new google.maps.Geocoder();
geocoder.geocode({
latLng: pos
}, function(responses) {
if (responses && responses.length > 0) {
document.getElementById('yourTextBoxId').value=responses[0].formatted_address;
} else {
document.getElementById('yourTextBoxId').value='Cannot determine address at this location.';
}
});
}
Here is a working example (puts the address received from the reverse geocoder in the infowindow)
Related
I have this query
var service = new google.maps.places.PlacesService(map);
var request = {
location: currentLocation,
radius: '4828.03',
type: ['workout gyms']
};
service.nearbySearch(request, callback);
And I am able to successfully place a marker on every location, but I want to make the marker clickable such that it displays the placeID in an infoWindow when clicked. Does anyone know how I could do this?
Modified code from the related question: Place nearbySearch Callback doesn't iterate through all elements (to return place details)
function callback(results, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
console.log("nearbySearch returned " + results.length + " results")
for (var i = 0; i < results.length; i++) {
// make a marker for each "place" in the result
createMarker(results[i]);
}
} else console.log("error: status=" + status);
}
function createMarker(place) {
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
google.maps.event.addListener(marker, 'click', function() {
// display the place "name" and "place_id" in the infowindow.
infowindow.setContent(place.name + "<br>" + place.place_id);
infowindow.open(map, this);
});
}
modified fiddle
code snippet:
function initMap() {
var lng;
var lat;
var my_loc = new google.maps.LatLng(37.4419, -122.1419);
map = new google.maps.Map(document.getElementById('map'), {
center: my_loc,
zoom: 10
});
geocoder = new google.maps.Geocoder();
infowindow = new google.maps.InfoWindow();
service = new google.maps.places.PlacesService(map);
var request = {
location: map.getCenter(),
radius: 4828.03,
type: ['workout gyms']
};
service.nearbySearch(request, callback);
}
function callback(results, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
console.log("nearbySearch returned " + results.length + " results")
for (var i = 0; i < results.length; i++) {
var id = results[i].place_id;
createMarker(results[i]);
}
} else console.log("error: status=" + status);
}
function createMarker(place) {
console.log("adding place " + place.name + " loc=" + place.geometry.location.toUrlValue(6));
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(place.name + "<br>" + place.place_id);
infowindow.open(map, this);
});
}
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?libraries=places&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="map"></div>
I'm trying to add some infowindow content to my markers on a google map. I can query my server, get some data, put the markers on the map. That works. What doesn't work is that nothing happens when I click on the marker. I would think that the infowindow would popup. Unfortunately, it has been so long since I have done google maps programming, I am effectively starting over. For some reason, the marker's click event is not being called. Any suggestions regarding my dumbness are appreciated. TIA
<script>
var map, geocoder;
var Markers = [];
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: { lat: 0.0, lng: 0.0 },
zoom: 12
});
if (!Modernizr.geolocation) {
alert("Your browser sucks. Get a new one, maybe one that is up to date and supports GPS.")
return;
}
else {
navigator.geolocation.getCurrentPosition(show_map);
}
}
function show_map(position) {
map.setZoom(12);
var Latitude = position.coords.latitude;
var Longitude = position.coords.longitude;
map.setCenter({ lat: Latitude, lng: Longitude });
var bounds = map.getBounds();
var url = "/api/xxxxxxxxjsonendpoint";
var lowerLeft = bounds.getSouthWest();
var upperRight = bounds.getNorthEast();
var lat0 = lowerLeft.lat();
var lng0 = lowerLeft.lng();
var lat1 = upperRight.lat();
var lng1 = upperRight.lng();
var geocoder = new google.maps.Geocoder();
var data = { LowerLeftLat: lat0, LowerLeftLng: lng0, UpperRightLat: lat1, UpperRightLng: lng1 };
$.get(url, data, function (result) {
for (var i = 0; i < result.length; i++) {
var address = result[i].Address1 + " " + (result[i].Address2 != null ? result[i].Address2 : "") + " " + result[i].City + " " + result[i].Province + " " + result[i].PostalCode + " " + result[i].Country;
var marker = new google.maps.Marker({
position: geocodeAddress(geocoder, map, address),
map: map,
title: address
});
var infowindow = new google.maps.InfoWindow({
content: i
});
makeInfoWindowEvent(map, infowindow, "test" + i, marker);
}
});
}
function geocodeAddress(geocoder, resultsMap, address) {
geocoder.geocode({ 'address': address }, function (results, status) {
if (status === 'OK') {
resultsMap.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: resultsMap,
position: results[0].geometry.location
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
function makeInfoWindowEvent(map, infowindow, contentString, marker) {
google.maps.event.addListener(marker, 'click', function () {
infowindow.setContent(contentString);
infowindow.open(map, marker);
});
}
</script>
Here is the most recent update of my code. Still no worky........
<script>
var map, geocoder;
var Markers = [];
var infowindow;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: { lat: 0.0, lng: 0.0 },
zoom: 12
});
infowindow = new google.maps.InfoWindow();
if (!Modernizr.geolocation) {
alert("Your browser sucks. Get a new one, maybe one that is up to date and supports GPS.")
return;
}
else {
navigator.geolocation.getCurrentPosition(show_map);
}
}
function show_map(position) {
map.setZoom(12);
var Latitude = position.coords.latitude;
var Longitude = position.coords.longitude;
map.setCenter({ lat: Latitude, lng: Longitude });
var bounds = map.getBounds();
var url = "/api/xxxxxxx/yyyyyyyyyy";
var lowerLeft = bounds.getSouthWest();
var upperRight = bounds.getNorthEast();
var lat0 = lowerLeft.lat();
var lng0 = lowerLeft.lng();
var lat1 = upperRight.lat();
var lng1 = upperRight.lng();
var geocoder = new google.maps.Geocoder();
var data = { LowerLeftLat: lat0, LowerLeftLng: lng0, UpperRightLat: lat1, UpperRightLng: lng1 };
$.get(url, data, function (result) {
for (var i = 0; i < result.length; i++) {
var address = result[i].Address1 + " " +
(result[i].Address2 != null ? result[i].Address2 : "") +
" " + result[i].City + " " + result[i].Province + " " +
result[i].PostalCode + " " + result[i].Country;
var marker = new google.maps.Marker({
position: geocodeAddress(geocoder, map, address),
map: map,
title: address,
content: address
});
makeInfoWindowEvent(infowindow, "test" + i, marker);
}
});
}
function geocodeAddress(geocoder, resultsMap, address) {
geocoder.geocode({ 'address': address }, function (results, status) {
if (status === 'OK') {
resultsMap.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: resultsMap,
position: results[0].geometry.location
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
function makeInfoWindowEvent(infowindow, contentString, marker) {
(function (zinfowindow, zcontentString, zmarker) {
zinfowindow.setContent(zcontentString);
google.maps.event.addListener(zmarker, 'click', function () {
zinfowindow.open(map, zmarker);
});
})(infowindow, contentString, marker);
}
</script>
function makeInfoWindowEvent(map, infowindow, contentString, marker) {
infowindow.setContent(contentString);
google.maps.event.addListener(marker, 'click', function () {
infowindow.open(map, marker);
});
}
Your code crash because when the listener is calling, the value of marker and infowindow have already changed. You can try something like this (just change the makeInfoWindowEvent function):
function makeInfoWindowEvent(map, infowindow, contentString, marker) {
google.maps.event.addListener(marker, 'click', function () {
infowindow.setContent(contentString);
infowindow.open(map, marker);
console.log (contentString);
console.log (marker);
});
}
Normally, the output will be always the same for contentString and marker.
In order to pass the real value of the marker, contentString and infowindow, you have to create an IIFE. Like this, the value of the variables will be copy inside the function:
function makeInfoWindowEvent(map, infowindow, contentString, marker) {
(function (zinfowindow, zcontentString, zmarker) {
zinfowindow.setContent(zcontentString);
google.maps.event.addListener(zmarker, 'click', function () {
zinfowindow.open(map, zmarker);
});
})(infowindow, contentString, marker);
}
However, you do not need to pass map as parameter because the value of map is always the same.
Tell me if you have some questions.
So I'm trying to build a simple web app that takes the address from the user and places a marker on that address. After that, the user can drag the marker to another location and the address field should update accordingly. The problem is I cannot get the address field to update automatically on dragend. The best I have done so far is to update when you click the marker but this is a horrible user experience.
tl;dr change the code so that the "address" field gets updated on dragend and not on click.
var geocoder = new google.maps.Geocoder();
var map;
var marker;
var infowindow = new google.maps.InfoWindow({
size: new google.maps.Size(150, 50)
});
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(37.9839, 23.7294);
var mapOptions = {
zoom: 16,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
google.maps.event.addListener(map, 'click', function() {
infowindow.close();
});
}
function geocodePosition(pos) {
geocoder.geocode({
latLng: pos
}, function(responses) {
if (responses && responses.length > 0) {
marker.formatted_address = responses[0].formatted_address;
} else {
marker.formatted_address = 'Cannot determine address at this location.';
}
infowindow.setContent("<b>" + marker.formatted_address + "</b>" + "<br> Drag the marker and click on it to update the address field!");
infowindow.open(map, marker);
});
}
function codeAddress() {
var address = document.getElementById('address').value;
geocoder.geocode({
'address': address
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
if (marker) {
marker.setMap(null);
if (infowindow) infowindow.close();
}
marker = new google.maps.Marker({
map: map,
draggable: true,
position: results[0].geometry.location
});
google.maps.event.addListener(marker, 'dragend', function() {
geocodePosition(marker.getPosition());
});
google.maps.event.addListener(marker, 'click', function() {
newAddress = marker.formatted_address;
document.getElementById("address").value = newAddress;
if (marker.formatted_address) {
infowindow.setContent("<b>" + marker.formatted_address + "</b>" + "<br> Drag the marker and click on it to update the address field!");
} else {
infowindow.setContent("<b>" + address + "</b>" + "<br> Drag the marker and click on it to update the address field!");
}
infowindow.open(map, marker);
});
google.maps.event.trigger(marker, 'click');
}
else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
google.maps.event.addDomListener(window, "load", initialize);
geocoding runs asynchronously, you must update the input when the response arrives, not immediately.
Possible approach to achieve it:
change
google.maps.event.addListener(marker, 'dragend', function() {
geocodePosition(marker.getPosition());
});
...to
google.maps.event.addListener(marker, 'dragend', function() {
var that=this;
geocodePosition(that.getPosition(),
function(){
google.maps.event.trigger(that, 'click');
});
});
now you have a callback-function which may be executed when the response arrives.
To call it change
function geocodePosition(pos) {
geocoder.geocode({
latLng: pos
}, function(responses) {
if (responses && responses.length > 0) {
marker.formatted_address = responses[0].formatted_address;
} else {
marker.formatted_address = 'Cannot determine address at this location.';
}
infowindow.setContent("<b>" + marker.formatted_address + "</b>" + "<br> Drag the marker and click on it to update the address field!");
infowindow.open(map, marker);
});
}
...to
function geocodePosition(pos,callback) {
geocoder.geocode({
latLng: pos
}, function(responses) {
if (responses && responses.length > 0) {
marker.formatted_address = responses[0].formatted_address;
} else {
marker.formatted_address = 'Cannot determine address at this location.';
}
infowindow.setContent("<b>" + marker.formatted_address + "</b>" + "<br> Drag the marker to update the address field!");
callback();//<--this will trigger the marker-click
infowindow.open(map, marker);
});
}
I've got a weird problem. It says f = undefined in infowindow.js. But I don't even have a file infowindow.js... This happens when I click on it. It has to show infowindow, but it doesn't.
Got the code from documentation here: LINK
Here's my code (address array is now adjusted, in my code there are normal addresses in it):
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 7,
center: { lat: 52.3, lng: 5.7 }
});
var geocoder = new google.maps.Geocoder();
var addresses = [
{
'adres': 'teststraat 21',
'plaats': 'Apeldoorn',
'postcode': '1234AB',
'telefoon': '0123456789',
'openingstijden': 'test'
},
{
'adres': 'teststraat 21',
'plaats': 'Apeldoorn',
'postcode': '1234AB',
'telefoon': '0123456789',
'openingstijden': 'test'
},
{
'adres': 'teststraat 21',
'plaats': 'Apeldoorn',
'postcode': '1234AB',
'telefoon': '0123456789',
'openingstijden': 'test'
},
];
geocodeAddress(geocoder, map, addresses);
}
function geocodeAddress(geocoder, resultsMap, addresses) {
for(var i = 0; i < addresses.length; i++) {
geocoder.geocode({'address': addresses[i]['adres'] + addresses[i]['plaats']}, function (results, status) {
if (status === google.maps.GeocoderStatus.OK) {
var counter = i - addresses.length;
var infowindow = new google.maps.InfoWindow({
content: 'test',
maxWidth: 200
});
var marker = new google.maps.Marker({
map: resultsMap,
position: results[0].geometry.location,
title: 'testadres ' + addresses[counter]['plaats'],
});
marker.addListener('click', function() {
infowindow.open(map, marker);
});
i++;
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
}
You use map instead of resultsMap in this piece of code:
The map object doesn't exist in this context. Should be:
infowindow.open(resultsMap, marker);
To close the staying infowindow before opening a new one, add only one infowindow instance and change it's content and position on marker click:
var infowindow = null;
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 7,
center: { lat: 52.3, lng: 5.7 }
});
var geocoder = new google.maps.Geocoder();
var addresses = [];
geocodeAddress(geocoder, map, addresses);
}
function geocodeAddress(geocoder, resultsMap, addresses) {
var infowindow = new google.maps.InfoWindow();
for(var i = 0; i < addresses.length; i++) {
geocoder.geocode({'address': addresses[i]['adres'] + " " + addresses[i]['plaats']}, function (results, status) {
if (status === google.maps.GeocoderStatus.OK) {
var counter = i - addresses.length;
var marker = new google.maps.Marker({
map: resultsMap,
position: results[0].geometry.location,
title: 'testadres ' + addresses[counter]['plaats'],
});
marker.addListener('click', function() {
infowindow.setContent('test content');
infowindow.open(resultsMap, marker);
});
i++;
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
}
<div id="map" style="height:400px; width:500px;"></div>
<script src="https://maps.googleapis.com/maps/api/js?callback=initMap"
async defer></script>
Even google logo, 'term of use' text, zoom buttons, marker also showing but map is not loading
my code
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places"></script>
<script>
var geocoder;
var map;
var infowindow;
var marker;
function initialize() {
var myCoordsLenght = 6;
var defaultLat = document.getElementById('latitude').value;
var defaultLng = document.getElementById('longitude').value;
if(defaultLat =="")
defaultLat =24;
if(defaultLng =="")
defaultLng =78;
var latlng1;
geocoder = new google.maps.Geocoder();
var ltlg = new google.maps.LatLng(defaultLat, defaultLng);
var mapOptions = {
center: ltlg,
zoom: 4
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var input = /** #type {HTMLInputElement} */(document.getElementById('pac-input'));
//var types = document.getElementById('type-selector');
//map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
//map.controls[google.maps.ControlPosition.TOP_LEFT].push(types);
var autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.bindTo('bounds', map);
infowindow = new google.maps.InfoWindow();
if(defaultLat == 24 && defaultLng ==78)
infowindow.setContent('Click on the Your Location (or)<br> Drag Marker to the Your Location');
else
{
geocoder.geocode({'latLng': ltlg}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
infowindow.setContent('<div>'+results[1].formatted_address+'</div>');
infowindow.open(map, marker);
}
} else
alert("Geocoder failed due to: " + status);
});
}
marker = new google.maps.Marker({
position: ltlg,
map: map,
draggable: true,
title: 'Click on Map/Click & Drag',
anchorPoint: new google.maps.Point(0, -29)
});
google.maps.event.addListener(map, 'click', function(evt) {
marker.setPosition(evt.latLng);
geocoder.geocode({'latLng': evt.latLng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0])
infowindow.setContent('<div>'+results[0].formatted_address+'</div>');
else
infowindow.setContent('No results found');
}
else
infowindow.setContent('Geocoder failed due to: ' + status);
});
document.getElementById('latitude').value = evt.latLng.lat();
document.getElementById('longitude').value = evt.latLng.lng();
});
google.maps.event.addListener(marker, 'dragend', function(evt){
geocoder.geocode({'latLng': evt.latLng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0])
infowindow.setContent('<div>'+results[0].formatted_address+'</div>');
else
infowindow.setContent('No results found');
}
else
infowindow.setContent('Geocoder failed due to: ' + status);
});
document.getElementById('latitude').value = evt.latLng.lat();
document.getElementById('longitude').value = evt.latLng.lng();
});
google.maps.event.addListener(marker, 'click', function () {
infowindow.open(map, marker);
});
google.maps.event.addListener(autocomplete, 'place_changed', function() {
infowindow.close();
marker.setVisible(false);
var place = autocomplete.getPlace();
if (!place.geometry)
return;
// If the place has a geometry, then present it on a map.
if (place.geometry.viewport)
map.fitBounds(place.geometry.viewport);
else {
map.setCenter(place.geometry.location);
map.setZoom(17); // Why 17? Because it looks good.
}
marker.setPosition(place.geometry.location); //place.geometry.location.lat();
marker.setVisible(true);
document.getElementById('latitude').value = place.geometry.location.lat();
document.getElementById('longitude').value = place.geometry.location.lng();
var address = '';
if (place.address_components) {
address = [
(place.address_components[0] && place.address_components[0].short_name || ''),
(place.address_components[1] && place.address_components[1].short_name || ''),
(place.address_components[2] && place.address_components[2].short_name || '')
].join(' ');
}
infowindow.setContent('<div><strong>' + place.name + '</strong><br>' + address);
infowindow.open(map, marker);
});
// Sets a listener on a radio button to change the filter type on Places
// Autocomplete.
function setupClickListener(id, types) {
var radioButton = document.getElementById(id);
google.maps.event.addDomListener(radioButton, 'click', function() {
autocomplete.setTypes(types);
});
}
setupClickListener('changetype-all', []);
setupClickListener('changetype-establishment', ['establishment']);
setupClickListener('changetype-geocode', ['geocode']);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
HTML
<div class="controls" id="map-canvas" style="width: 650px;height:400px;"></div>
It shows error in console as
Firefox => TypeError: a is null in main.js
chrome => Uncaught TypeError: Cannot read property 'addEventListener' of null in main.js
From the fiddle's html and the error info you had given, my guess would be Maps are loaded properly but these lines are causing your error
function setupClickListener(id, types) {
var radioButton = document.getElementById(id);
if(radioButton){
google.maps.event.addDomListener(radioButton, 'click', function() {
autocomplete.setTypes(types);
});
}
}
The ids that you are passing are not present in your html!
setupClickListener('changetype-all', []);
setupClickListener('changetype-establishment', ['establishment']);
setupClickListener('changetype-geocode', ['geocode']);
The radioButton object is null and hence your error. A simple if will solve the issue