info window not showing reverse geocoded address Google Maps V3 - google-maps

I'm coding a script that allows you to place a marker based on where you mouse click. I got that down. However, I cannot seem to get the infowindow to pop up when I pass in the reverse geocoded lat and lng. Could someone help me? Thanks!
Here is my code:
var geocoder;
function initialize()
{
geocoder = new google.maps.Geocoder();
var event = google.maps.event.addListener;
// intializing and creating the map.
var mapOptions = {
zoom: 4,
center: new google.maps.LatLng(-25.363882, 131.044922),
mapTypeId: google.maps.MapTypeId.TERRAIN
};
var map = new google.maps.Map(document.getElementById('map'),
mapOptions);
event(map,'click',function(e){
var marker = placeMarker_and_attachMessage(e.latLng,map,count);
});
} // end of initalize.
/* place down marker based on where you click the mouse over a certain area on the map.
An infowindow should appear with the location of your marker.
*/
function placeMarker_and_attachMessage(position,map,num)
{
var event = google.maps.event.addListener;
var marker = new google.maps.Marker({
position: position,
map: map
});
var infowindow = new google.maps.InfoWindow({
content: info_text(position)
});
event(marker,'mouseover',function(){
infowindow.open(map,this);
});
event(marker,'mouseout',function(){
infowindow.close();
});
} // end of function.
// Takes in the position passed by the 'placeMarker_and_attachMessage' function and returns a human readable string
function info_text(position)
{
var location = position;
var latlngStr = location.split(',',2);
var lat = parseFloat(latlngStr[0]);
var lng = parseFloat(latlngStr[1]);
var latlng = new google.maps.LatLng(lat,lng);
geocoder.geocode({'latLng': latlng}, function(results, status)
{
if (status == google.maps.GeocoderStatus.OK)
{
return results;
}
else
{
alert('could not pinpoint location');
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);

In the code you posted, count is not defined in
var marker = placeMarker_and_attachMessage(e.latLng,map,count);

Related

Show User location on google maps

First thing is I will tell you I am new to google maps and some of it is very confusing to me. What I need to do is show a users location and have the appropriate markers show up. I have the database all ready and somewhat of the Google map.
What I am working with is an example from here. What I can either get is the markers if I use a static LatLng or just the users dynamic location with no markers.
Need help please. And if you downvote this post please let me know why.
Code I am using can be found at https://jsfiddle.net/8q1apmdy/9/ and show where in the blow code is where I am missing something, most likely small or in the wrong position.
function initMap() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition((position) => {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
});
var map = new google.maps.Map(document.getElementById('map'), {
center: pos,
zoom: 12
});
}
a) While running your code locally, I was getting 'pos' undefined, so I moved the following code 'var map = new google.maps.Map(..' inside the getCurrentPosition(){...
b) Then I got another error ' InvalidValueError: setMap: not an instance of Map;' so created a 'var map' globally.
Loaded the map successfully, but still markers were not loaded. while debugging your code at this point 'var marker = new google.maps.Marker({...' it is iterating for all markers from xml but somehow markers are not adding to the map..dont know the reason yet?
So I have tried in a different way. Please see all markers from xml displayed on map. Here I am just getting the 'name' in marker, you might need to add other parameters like id, address etc.
JSFiddle added for reference
var infowindow;
var map;
//var downloadUrl;
function initialize() {
var mapOptions = {
zoom: 12,
center: new google.maps.LatLng(-33.868820, 151.209290),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById('map'), mapOptions);
downloadUrl("https://storage.googleapis.com/mapsdevsite/json/mapmarkers2.xml", function(data) {
var bounds = new google.maps.LatLngBounds();
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName('marker');
for (var i = 0; i < markers.length; i++) {
var id = markers[i].getAttribute('id');
var address = markers[i].getAttribute('address');
var type = markers[i].getAttribute('type');
var latlng = new google.maps.LatLng(parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
bounds.extend(latlng);
var marker = createMarker(id, markers[i].getAttribute("name"), address, latlng, type);
}//finish loop
//map.fitBounds(bounds);
}); //end downloadurl
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}
}
function createMarker(id, name, address, latlng, type) {
var marker = new google.maps.Marker({
position: latlng,
map: map
});
google.maps.event.addListener(marker, "click", function() {
if (infowindow) infowindow.close();
infowindow = new google.maps.InfoWindow({content: name});
infowindow.open(map, marker);
});
return marker;
}
JSFiddle

Pass Google Maps SearchBox result to Directions Service

After reading documentation for the SearchBox class, the Places library including the AutoComplete class, and the Directions service, I cannot figure out how to pass the address selected by a user from the SearchBox to the Directions service to draw the map. The map and marker display correctly, and the SearchBox displays and functions correctly. On the "place_change" event, though, nothing happens. My code:
var rawlatitude = <?php echo $loc_lat; ?>;
var rawlongitude = <?php echo $loc_long; ?>;
var latitude = parseFloat(rawlatitude);
var longitude = parseFloat(rawlongitude);
var latlong = new google.maps.LatLng(latitude,longitude);
google.maps.event.addDomListener(window, 'load',initMap(latitude,longitude));
function initMap(lat,lng) {
// instantiate directions service object
var directionsService = new google.maps.DirectionsService;
// create map
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 16,
center: latlong
});
// add marker
var marker = new google.maps.Marker({
position: latlong,
map: map
});
// put address search box into map
var input = document.getElementById('pac-input');
var searchBox = new google.maps.places.SearchBox(input);
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
// create directions renderer and bind it to map
var directionsDisplay = new google.maps.DirectionsRenderer({map: map});
// listen to and respond to address search
var onChangeHandler = function() {
var location = searchBox.getPlaces();
var start = location.place_id;
calculateAndDisplayRoute(directionsDisplay, directionsService, map, start);
};
google.maps.event.addListener(searchBox, 'place_change', onChangeHandler);
}
function calculateAndDisplayRoute(directionsDisplay, directionsService, map, start) {
directionsService.route({
origin: start,
destination: latlong,
travelMode: google.maps.TravelMode.DRIVING
}, function(response, status) {
if(status === google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
As Dr.Molle observed in his comment,
There is no place_changed-event for a SearchBox, it's an event for Autocomplete. The event for a SearchBox is called places_changed.
Also note that a SearchBox.getPlaces() returns an array with places
working fiddle
working code snippet:
var rawlatitude = 40.7127837;
var rawlongitude = -74.0059413;
var latitude = parseFloat(rawlatitude);
var longitude = parseFloat(rawlongitude);
var latlong = new google.maps.LatLng(latitude, longitude);
var viewport = {
"south": 40.4960439,
"west": -74.2557349,
"north": 40.91525559999999,
"east": -73.7002721
};
google.maps.event.addDomListener(window, 'load', function() {
initMap(40.735657, -74.1723667);
});
function initMap(lat, lng) {
// instantiate directions service object
var directionsService = new google.maps.DirectionsService;
// create map
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 16,
center: latlong
});
// add marker
var marker = new google.maps.Marker({
position: latlong,
draggable: true,
map: map
});
// put address search box into map
var input = document.getElementById('pac-input');
var searchBox = new google.maps.places.SearchBox(input, {
bounds: viewport
});
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
// create directions renderer and bind it to map
var directionsDisplay = new google.maps.DirectionsRenderer({
map: map
});
// listen to and respond to address search
var onChangeHandler = function() {
var locations = searchBox.getPlaces();
var start = locations[0].place_id;
var bounds = new google.maps.LatLngBounds();
bounds.extend(latlong);
bounds.extend(locations[0].geometry.location);
map.fitBounds(bounds);
var marker = new google.maps.Marker({
position: locations[0].geometry.location,
map: map,
title: locations[0].name
})
calculateAndDisplayRoute(directionsDisplay, directionsService, map, start);
};
google.maps.event.addListener(searchBox, 'places_changed', onChangeHandler);
}
function calculateAndDisplayRoute(directionsDisplay, directionsService, map, start) {
directionsService.route({
origin: {
placeId: start
},
destination: {
location: latlong
},
travelMode: google.maps.TravelMode.DRIVING
}, function(response, status) {
if (status === google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0;
padding: 0;
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=places"></script>
<input id="pac-input" />
<div id="map"></div>

Showing street address in google maps API v2, need it in v3 now

I'm using google maps api v2 below to show address in var address line on the map, and I want to have this in api v3. Does anyone know how to make this as google maps api v3?
<script type="text/javascript">
//<![CDATA[
var geocoder;
var map;
var address = "425 West 53rd St,New York,NY,";
// On page load, call this function
function load()
{
// Create new map object
map = new GMap2(document.getElementById("map"));
map.addControl(new GSmallMapControl());
// Create new geocoding object
geocoder = new GClientGeocoder();
// Retrieve location information, pass it to addToMap()
geocoder.getLocations(address, addToMap);
}
// This function adds the point to the map
function addToMap(response)
{
// Retrieve the object
place = response.Placemark[0];
// Retrieve the latitude and longitude
point = new GLatLng(place.Point.coordinates[1],
place.Point.coordinates[0]);
// Center the map on this point
map.setCenter(point, 15);
// Create a marker
marker = new GMarker(point);
// Add the marker to map
map.addOverlay(marker);
} //]]>
</script>
<script src="http://maps.google.com/maps?file=api&v=2&key=xxxxxxxx" type="text/javascript"></script><div id="map"></div>
Simple example from documentation, with your address instead of the "input field"
var geocoder;
var map;
var address = "425 West 53rd St,New York,NY,";
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(-34.397, 150.644);
var mapOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById('map'), mapOptions);
codeAddress();
}
function codeAddress() {
geocoder.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: results[0].geometry.location
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
jsfiddle

Google maps infowindow

I am trying to create listeners for some map markers. I can create the markers and they are on the map but, no matter which marker I click on it tells me "Uncaught TypeError: Cannot call method 'open' of undefined" . When I break at the open code it is showing markers[46] which is one more that the highest index. And it doesnt matter which marker I click on its always the same index.
EDIT: I edited the code and pasted all of it. No errors, but nothing happens when I click a marker. I am looking in Chrome and it looks like there isnt a event handler registered
<script>
var map;
var nav = [];
$(document).ready(function () {
//initialise a map
init();
var infowindow = new google.maps.InfoWindow({});
$.get("xxxxxx.kml", function (data) {
html = "";
//loop through placemarks tags
i = 1;
$(data).find("Placemark").each(function (index, value) {
//get coordinates and place name
coords = $(this).find("coordinates").text();
contentString = $(this).find("description").text();
var partsOfStr = coords.split(',');
var lat = parseFloat(partsOfStr[0]);
var lng = parseFloat(partsOfStr[1]);
var myLatLng = new google.maps.LatLng(lng, lat);
place = $(this).find("name").text();
createMarker(myLatLng, place, contentString, i)
//store as JSON
c = coords.split(",")
nav.push({
"place": place,
"lat": c[0],
"lng": c[1]
})
//output as a navigation
html += "<li>" + place + "</li>";
i++;
});
//output as a navigation
$(".navigation").append(html);
//bind clicks on your navigation to scroll to a placemark
$(".navigation li").bind("click", function () {
panToPoint = new google.maps.LatLng(nav[$(this).index()].lng, nav[$(this).index()].lat)
map.panTo(panToPoint);
})
});
markers = [];
function createMarker(myLatLng, title, contentString, i) {
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: title
});
google.maps.event.addListener(markers, 'click', function () {
infoWindow.setContent(contentString);
infowindow.open(map, markers[i]);
});
markers[i] = marker;
return marker
}
function init() {
//google.maps.event.addDomListener(window, 'init', Initialize);
var latlng = new google.maps.LatLng(39.047050, -77.131409);
var myOptions = {
zoom: 4,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map"), myOptions);
}
})
This is almost a FAQ. When your loop ends, the value of i is 46 (based on your statement). There is no marker 46, so all the click listeners fail. It can be solved with function closure (a createMarker function which holds the association between the marker and the infowindow contents).
Something like this in your example (not tested), call it from inside your marker creation loop, requires a global markers array, but doesn't require the global infowindow array:
//global markers array
markers = [];
// global infowindow
var infowindow = new google.maps.InfoWindow({});
// createMarker function
function createMarker(myLatLng, title, contentString, i)
{
var marker = new google.maps.Marker({
position: myLatlng ,
map: map,
title:title
});
google.maps.event.addListener(markers, 'click', function() {
infoWindow.setContent(contentString);
infowindow.open(map,markers[i]);
});
markers[i] = marker;
return marker
}

InfoWindow on Marker using MarkerClusterer

This is my html code. I've try anything to add an infowindow on the markers but it don't wanna work. My data is loading from the "Alle_Ortswahlen.page1.xml" file.
Do anyone have an idea how can I add infoWindow to each marker?
<script type="text/javascript">
google.load('maps', '3', {
other_params: 'sensor=false'
});
google.setOnLoadCallback(initialize);
function initialize() {
var stack = [];
var center = new google.maps.LatLng(48.136, 11.586);
var options = {
'zoom': 5,
'center': center,
'mapTypeId': google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), options);
GDownloadUrl("Alle_Ortswahlen.page1.xml", function(doc) {
var xmlDoc = GXml.parse(doc);
var markers = xmlDoc.documentElement.getElementsByTagName("ROW");
for (var i = 0; i < markers.length; i++) {
// obtain the attribues of each marker
var lat = parseFloat(markers[i].getAttribute("Field4"));
var lng = parseFloat(markers[i].getAttribute("Field6"));
var marker = new google.maps.Marker({
position : new google.maps.LatLng(lat, lng),
map: map,
title:"This is a marker"
});
stack.push(marker);
}
var mc = new MarkerClusterer(map,stack);
});
}
</script>
Before the for cycle, make an empty infowindow object.
var infowindow = new google.maps.InfoWindow();
Than in the for cycle, after the marker, add an event listener, like this:
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent("You might put some content here from your XML");
infowindow.open(map, marker);
}
})(marker, i));
There is some closure magic happening when passing the callback argument to the addListener method. If you are not familiar with it, take a look at here:
Mozilla Dev Center: Working with Closures
So, your code should look something like this:
google.load('maps', '3', {
other_params: 'sensor=false'
});
google.setOnLoadCallback(initialize);
function initialize() {
var stack = [];
var center = new google.maps.LatLng(48.136, 11.586);
var options = {
'zoom': 5,
'center': center,
'mapTypeId': google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), options);
var infowindow = new google.maps.InfoWindow();
GDownloadUrl("Alle_Ortswahlen.page1.xml", function(doc) {
var xmlDoc = GXml.parse(doc);
var markers = xmlDoc.documentElement.getElementsByTagName("ROW");
for (var i = 0; i < markers.length; i++) {
// obtain the attribues of each marker
var lat = parseFloat(markers[i].getAttribute("Field4"));
var lng = parseFloat(markers[i].getAttribute("Field6"));
var marker = new google.maps.Marker({
position : new google.maps.LatLng(lat, lng),
map: map,
title:"This is a marker"
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent("You might put some content here from your XML");
infowindow.open(map, marker);
}
})(marker, i));
stack.push(marker);
}
var mc = new MarkerClusterer(map,stack);
});
}
So what you need to do is add some code, inside your for-loop, associating an infowindow onclick event handler with each marker. I'm assuming you only want to have 1 infowindow showing at a time, i.e. you click on a marker, the infowindow appears with relevant content. If you then click on another marker, the first infowindow disappears, and a new one reappears attached to the other marker. Rather than having multiple infowindows all visible at the same time.
GDownloadUrl("Alle_Ortswahlen.page1.xml", function(doc) {
var xmlDoc = GXml.parse(doc);
var markers = xmlDoc.documentElement.getElementsByTagName("ROW");
// just create one infowindow without any content in it
var infowindow = new google.maps.InfoWindow({
content: ''
});
for (var i = 0; i < markers.length; i++) {
// obtain the attribues of each marker
var lat = parseFloat(markers[i].getAttribute("Field4"));
var lng = parseFloat(markers[i].getAttribute("Field6"));
var marker = new google.maps.Marker({
position : new google.maps.LatLng(lat, lng),
map: map,
title:"This is a marker"
});
// add an event listener for this marker
google.maps.event.addListener(marker , 'click', function() {
// assuming you have some content in a field called Field123
infowindow.setContent(markers[i].getAttribute("Field123"));
infowindow.open(map, this);
});
stack.push(marker);
}
var mc = new MarkerClusterer(map,stack);
});