How to display certain names in google maps infowindow marker - javascript

I'm kind of stuck and was wondering if someone could help, here is a snippet of my code:
function test(person,address)
{
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: new google.maps.LatLng(43.761539, -79.411079),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow()
var marker, i;
var clatlng, clat, clng;
for (i = 0; i < address.length; i++) {
geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': address[i]}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
clat = results[0].geometry.location.lat();
clng = results[0].geometry.location.lng();
clatlng = new google.maps.LatLng(clat, clng);
marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
google.maps.event.addListener(marker, 'click', (function(marker) {
//cant add information here dont know why...
return function() {
infowindow.setContent(person[0].cName + "<br>" + results[0].formatted_address);
infowindow.open(map, marker);
}
})(marker));
}
});
}//for
}//function
I'm passing an array of addresses and names. I've been trying to get each marker to display the person's name and address upon clicking on the infowindow of the marker on the map. This is where I'm having issues, I solved the address issue by just using the results[0].formatted_address but am unsure on how to display the specific user to that marker. Any tips would be appreciated.

You need function closure on the name as well as the marker in the click listener for the marker. As the name of the person needs to be available in the callback for the geocoder as well, you need function closure on the geocoder callback function as well.
Related questions
Google Maps V3 - I cannot reconcile closure
JS Geocoder cannot assign Global Variable for Google Maps Variable
proof of concept fiddle
code snippet:
function test(person, address) {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 5,
center: new google.maps.LatLng(43.761539, -79.411079),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow()
var marker, i;
var clatlng, clat, clng;
for (i = 0; i < address.length; i++) {
geocoder = new google.maps.Geocoder();
geocoder.geocode({
'address': address[i]
}, (function(name) {
return function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
clat = results[0].geometry.location.lat();
clng = results[0].geometry.location.lng();
clatlng = new google.maps.LatLng(clat, clng);
marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
google.maps.event.addListener(marker, 'click', (function(marker, name) {
//cant add information here dont know why...
return function() {
infowindow.setContent(name + "<br>" + results[0].formatted_address);
infowindow.open(map, marker);
}
})(marker, name));
}
}
})(person[i]));
} //for
} //function
function initialize() {
test(["fred", "george", "frank"], ["New York, NY", "Newark, NJ", "Toronto, CA"]);
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map"></div>

Related

Why is my map not displaying the place name in the map after getting the current location?

I have made a map with getting the current location,inside the getPosition is getting also the place name which I also made a reverse geocoding that returns the place name from a coordinate, I wonder what's wrong my code that it did not return the place name and even the marker with my code for reverse geocoding.
In the console I get this
<p id="curr" style="">current lat lng</p>
function getPosition() {
navigator.geolocation.getCurrentPosition(position => {
currentLatLon = [position.coords.latitude, position.coords.longitude];
infowindow = new google.maps.InfoWindow();
map = new google.maps.Map(
document.getElementById('map'), {
center: new google.maps.LatLng(...currentLatLon),
zoom: 20
});
var geocoder = new google.maps.Geocoder();
service = new google.maps.places.PlacesService(map);
document.getElementById("curr").innerHTML=currentLatLon;
geocodeLatLng(geocoder,map,infowindow);
});
}
function geocodeLatLng(geocoder, map, infowindow) {
var input = document.getElementById('curr').value;
var latlngStr = input.split(',', 2);
var latlng = {lat: parseFloat(latlngStr[0]), lng: parseFloat(latlngStr[1])};
geocoder.geocode({'location': latlng}, function(results, status) {
if (status === 'OK') {
if (results[0]) {
map.setZoom(11);
var marker = new google.maps.Marker({
position: latlng,
map: map
});
infowindow.setContent(results[0].formatted_address);
infowindow.open(map, marker);
} else {
window.alert('No results found');
}
} else {
window.alert('Geocoder failed due to: ' + status);
}
});
}

Simple Geocoding Map in JQuery

How do I make a simple map in Jquery that plots only one location. Here is the code I have now. this plots an array of locations, but I just need a simple map that will plot one point in Lng,Lat format. I am using the google geocoder for this.
var geocoder;
var map;
var markersArray = [];
var bounds;
var infowindow = new google.maps.InfoWindow({
content: ''
});
function initialize() {
geocoder = new google.maps.Geocoder();
bounds = new google.maps.LatLngBounds();
var myOptions = {
zoom: 2,
mapTypeId: google.maps.MapTypeId.ROADMAP,
navigationControlOptions: {
style: google.maps.NavigationControlStyle.SMALL
}
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
geocoder.geocode({
'address': '5th Avenus New Yort'
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
bounds.extend(results[0].geometry.location);
markersArray.push(marker);
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
plotMarkers();
}
var locationsArray = [
['Google Official', '1600 Amphitheatre Parkway, Mountain View, USA'],
['Google 1', '112 S. Main St., Ann Arbor, USA'],
['Google 2', '10 10th Street NE, Suite 600 USA']
];
function plotMarkers() {
var i;
for (i = 0; i < locationsArray.length; i++) {
codeAddresses(locationsArray[i]);
}
}
function codeAddresses(address) {
geocoder.geocode({
'address': address[1]
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(address[0]);
infowindow.open(map, this);
});
bounds.extend(results[0].geometry.location);
markersArray.push(marker);
} else {
alert("Geocode was not successful for the following reason: " + status);
}
map.fitBounds(bounds);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
I then call this in my file with:
<body>
<div id="map_canvas" style="width: 100%; height: 700px;"></div>
</body>
</html>
I need the new map to plot one lat and lng point along with posting the listing the location in the textbook as above. I can not figure out how to do this without an array.
It seems like you're using an example that shows multiple markers.
I haven't tested it, but I think this JavaScript is close:
var geocoder;
var map;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(-34.397, 150.644);
var mapOptions = {
zoom: 8,
center: latlng
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
geocoder.geocode( { 'address': '5th Avenue New York' }, 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);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
Review this for more information: https://developers.google.com/maps/documentation/javascript/geocoding

Geocoder is automatically panning google map to the left

I am creating a page with a marker that stays fixed at the center of a map, even if the user pans/zoom the map. When the user clicks on the marker it shows the full address of the marker.
The problem is that the infoWindow.setContent() shows a string when I supply one, but pans the map to the left (and doesnt show the infoWindow) when I supply results[0].formatted_address.
The code below is the reverse geocoding I have. The alert function (which I have uncommented) shows the address correctly.
var geocoder = new google.maps.Geocoder();
geocoder.geocode({'latLng': input}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
//alert(results[0].formatted_address);
infoWindow.setContent(results[0].formatted_address);
infoWindow.open(map,marker);
} else {
alert('No results found');
}
} else {
alert('Geocoder failed due to: ' + status);
}
});
And my complete Javascript Code is:
var map;
var marker;
var infoWindow = new google.maps.InfoWindow();
function initialize() {
function setUpMap(){
var mapOptions = {
zoom: 14,
center: new google.maps.LatLng(22.519422, 88.35741400000006),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map_canvas'),mapOptions);
google.maps.event.addListener(map, 'center_changed', function() {
removeMarker();
});
google.maps.event.addListener(map, 'idle', function() {
setMarker();
});
}
function removeMarker(){
marker.setMap(null);
}
function setMarker(){
marker = new google.maps.Marker({
position: map.getCenter(),
map: map,
title:"Hello World!"
});
google.maps.event.addListener(marker, 'click', function() {
var input = marker.getPosition();
var geocoder = new google.maps.Geocoder();
geocoder.geocode({'latLng': input}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
//alert(results[0].formatted_address);
infoWindow.setContent(results[0].formatted_address);
infoWindow.open(map,marker);
} else {
alert('No results found');
}
} else {
alert('Geocoder failed due to: ' + status);
}
});
});
}
setUpMap();
}
google.maps.event.addDomListener(window, 'load', initialize);
I think the problem is that, when the user clicks on the marker, somehow setMarker() gets called. I can't really find out where the problem is coming from. Can anyone help me find it?
It's forced by a interaction between the center_changed-handler and the autoPan of the infoWindow.
When you open a infoWindow the API by default tries to pan the map to be able to show the infoWindow at the best position. But when this happens the center of the map changes, the marker will be removed(that's why you don't see the infowindow). You must set the disableAutoPan-option of the infoWindow to true.
Modified code:
function initialize() {
function setUpMap() {
var mapOptions = {
zoom: 14,
center: new google.maps.LatLng(22.519422, 88.35741400000006),
mapTypeId: google.maps.MapTypeId.ROADMAP
},
map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions),
infoWindow = new google.maps.InfoWindow({
disableAutoPan: true
}),
marker = setMarker(map, infoWindow);
google.maps.event.addListener(map, 'center_changed', function() {
infoWindow.close();
marker.setPosition(this.getCenter());
});
}
function setMarker(map, infoWindow) {
var marker = new google.maps.Marker({
position: map.getCenter(),
map: map,
title: "Hello World!"
});
google.maps.event.addListener(marker, 'click', function() {
var input = marker.getPosition();
var geocoder = new google.maps.Geocoder();
geocoder.geocode({
'latLng': input
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
console.log(results)
if (results[0]) {
console.log(results[0].formatted_address)
//alert(results[0].formatted_address);
infoWindow.setOptions({
content: '<div style="xwidth:200px">' + results[0].formatted_address + '</div>'
});
infoWindow.open(map, marker);
} else {
alert('No results found');
}
} else {
alert('Geocoder failed due to: ' + status);
}
});
});
return marker;
}
setUpMap();
}
google.maps.event.addDomListener(window, 'load', initialize);
html {
height: 100%
}
body {
height: 100%;
margin: 0;
padding: 0
}
#map_canvas {
height: 100%
}
<script src="https://maps.googleapis.com/maps/api/js?v=3"></script>
<div id="map_canvas"></div>

infowindow.setContent all the same thing...dealing with closures/Google Maps api

I've been wrestling with this infowindow.setContent(address); for hours. Based on what I've read on here I know it has to do something with closures but I can't get it to work. Both of my info windows are the same right now.
Here's the test site right now, sorry for the poor appearance :)
http://testsite.edwardgranger.com/2013/12/05/hello-world/
PHP & js code:
<script type="text/javascript">
var o = <?php echo json_encode($m_userArray); ?>
</script>
<script src="http://maps.google.com/maps/api/js?sensor=false"
type="text/javascript"></script>
<div id="map" style="width: 500px; height: 400px;"></div>
<script type="text/javascript">
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: new google.maps.LatLng(-33.92, 151.25),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var marker;
var i;
var geocoder = new google.maps.Geocoder();
var infowindow = new google.maps.InfoWindow();
for(var i = 3; i <= 4; i++) {
var address = window.o[i].address;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(address);
infowindow.open(map, marker);
}
})(marker, i));
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
</script>
I've tried a few different concepts but honestly I just found out about closures tonight and I understand them on a higher level but trying to navigate my code is a chore, a second set of eyes would be great right now.

Google maps zoom level for country

I'm having a problem working out how to set the zoom level for different countries, I have managed to get the map working and displaying the country, just cannot seem to work out how to set the zoom level.
Any help would be appreciated.
Thanks
George
<script type="text/javascript">
var infowindow = null;
$(document).ready(function () { initialize(); });
function initialize() {
//var geocoder = new google.maps.Geocoder();
//geocoder.geocode({ 'address': address }, function (results, status) {
// if (status == google.maps.GeocoderStatus.OK) {
// map.setCenter(results[0].geometry.location);
// map.fitBounds(results[0].geometry.viewport);
// }
//});
var centerMap = new google.maps.LatLng(#Html.Raw(#item.strLatLong));
var myOptions = {
zoom: 4, //<<-------How can I chnage this
center: centerMap,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("WeatherMapLocation"), myOptions);
setMarkers(map, sites);
infowindow = new google.maps.InfoWindow({
content: "loading..."
});
var bikeLayer = new google.maps.BicyclingLayer();
bikeLayer.setMap(map);
}
function setMarkers(map, markers) {
for (var i = 0; i < markers.length; i++) {
var sites = markers[i];
var siteLatLng = new google.maps.LatLng(sites[1], sites[2]);
var marker = new google.maps.Marker({
position: siteLatLng,
map: map,
title: sites[0],
zIndex: sites[3],
html: sites[4]
});
var contentString = "Some content";
google.maps.event.addListener(marker, "click", function () {
infowindow.setContent(this.html);
infowindow.open(map, this);
});
}
}
</script>
From the documentation on the Geocoder, there is a viewport and a bounds returned in the geocoder's response which can be used to center and zoom the map on the result.
if (results && results[0] && results[0].geometry && results[0].geometry.viewport)
map.fitBounds(results[0].geometry.viewport);
working example

Categories

Resources