Google map API displaying marker location in an infowindow - javascript

I have a javascript array of locations (jarray), which I am looping over and adding a marker of each location onto a google map. Along with those markers I would like to add an infowindow displaying the marker's location. The code below displays the same latitude and longitude location in each of marker's infowindows. I would like for each marker to have its own address in its infowindow. I have also tried setting the content of the infowindow to results[0].geometry.location, address, and jarray[i] all to no success. Any ideas are greatly appreciated.
for(var i = 0; i < jarray.length; i++){
geocoder.geocode({'address': jarray[i]},
function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
var marker = new google.maps.Marker({
position: results[0].geometry.location,
map: map,
title: "Marker",
icon: image
});
var infowindow = new google.maps.InfoWindow({
content: "<p>"+marker.position+"</p>"
});
marker.addListener('mouseover', function() {
infowindow.open(map, marker);
});

I don't think a google maps api marker has a location property - you can use position - the method is marker.getPosition()
https://developers.google.com/maps/documentation/javascript/reference?hl=en#Marker
You can then use that position to an address by usign the geocoding (if you need that)
https://developers.google.com/maps/documentation/geocoding/intro

insted of marker.location, use the jarray location itself. You can adapt this code to suit you since I dont know the contents of your jarray.
var infowindow = new google.maps.InfoWindow({
infowindow.setContent(jarray[i]['lat'] +" " + jarray[i]['lat']);
infowindow.open(map, marker);
});

Related

Nearby Places Google Maps Places API

First of all, I just started with JavaScript, so I'm not really good at it. I am making an app, using the Google Maps Places API, in which you can push a button and get your location, push another button and get nearby places (for example stores or bars) based on your location. Getting the location of the device works, but my code doesn't display the nearby places. It does go to the location, but it doesn't show the markers of the nearby places. I don't know what is going wrong, but I think it might have to do with the code for the markers or with the sequence of the code.
I am using Intel XDK (HTML5 + Cordova and the App Designer) and the Google Maps Places API. Right now it all happens when one button (with id="myloc-btn") is pushed, but (if both the location and the nearby places work) I want to seperate them in two buttons, one to show the location and one to show the nearby places.
Below is my javascript code. I have commented out the marker for the location of the device I originally had, because I thought it might be in the way of the markers for the nearby places.
Anyone know what's wrong or can help me?
Thanks in advance!
---UPDATE---
I tried the search nearby places from the Google Maps documentation (https://developers.google.com/maps/documentation/javascript/examples/place-search), with a set location (I basically copied and pasted the code), but that doesn't work either. Again it goes to the right location, but it doesn't display any markers. I tried it both in the simulator and on my phone, but it both has the same result. I don't know why the markers don't show
var map;
var service;
var infoWindow;
var pos;
var marker = [];
//var labels = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
//var labelIndex = 0;
function register_event_handlers() {
$(document).on("click", "#myloc-btn", function(evt) {
initMap();
});
function initMap() {
map = new google.maps.Map(document.getElementById('gmap'), {zoom: 14});
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
//addMarker(pos, map);
map.setCenter(pos);
}, function() {
handleLocationError(true, infoWindow, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
}
var request = {
location: pos,
radius: 5000,
type: ['store']
};
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.nearbySearch(request, callback);
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
}
}
}
}
function handleLocationError(browserHasGeolocation, infoWindow, pos) {
infoWindow.setPosition(pos);
infoWindow.setContent(browserHasGeolocation ?
'Error: The Geolocation service failed.' :
'Error: Your browser doesn\'t support geolocation.');
}
/*
function addMarker(location, map) {
var marker = new google.maps.Marker({
map: map,
// Define the place with a location, a query string and a label.
place: {
location: location,
query: 'This is my location'
},
label: labels[labelIndex++ % labels.length],
});
// Construct a new InfoWindow.
var infoWindow = new google.maps.InfoWindow({
content: 'Here I am!'
});
// Opens the InfoWindow when marker is clicked.
marker.addListener('click', function() {
infoWindow.open(map, marker);
});
}
*/
function createMarker(place) {
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);
infowindow.open(map, this);
});
}
document.addEventListener("app.Ready", register_event_handlers, false);
})();
In the callback provided to getCurrentPosition(), you're setting pos. However, this callback will get called after the phone has determined the location, i.e. at some random point in the future. Which is long after you're trying to use that pos in your request for the places. You need to move the places code in its own function, then call it while passing the map and pos, after you have centered the map. Almost exactly what you already did with addMarker().

Google Maps API - Link to place detail page

I have a custom Google Maps where marker are populate dynamically and I try to redirect the marker link to the corresponding place details' page on Google Maps. For example, on marker click, I would like to open a new window to this link : https://www.google.com/maps/place/PMBCOM/#46.381949,6.236581,17z/data=!3m1!4b1!4m2!3m1!1s0x478c372f7df47135:0xff206d31a973eded
For now, I am able to redirect to the address, but it does not show the full Google My Business panel like on my previous link. Any ideas ?
Here is my code :
function initMap() {
var myLatlng = new google.maps.LatLng(agence[0], agence[1]);
var map = new google.maps.Map(document.getElementById('maps'), {
center: myLatlng,
zoom:17
});
var infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.getDetails({
placeId: 'ChIJ71BChS4ujEcRclm9twk3Y04'
}, function(place, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location,
title: place.name,
url: 'https://www.google.com/maps/place/'+place.formatted_address
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(place.name);
infowindow.open(map, this);
window.open(marker.url);
});
}
});
}
google.maps.event.addDomListener(window, 'load', initMap);
Thanks for your help
look this part
url: 'https://www.google.com/maps/place/'+place.formatted_address
google cannot locate this company in this way
change to
url: place.url
I think this is what you want

How to pass a variable into a function defined in the argument of another function in JavaScript? [duplicate]

This question already has answers here:
Google Maps : Issue regarding marker icons and geocoding
(1 answer)
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 8 years ago.
I am working on Google Maps API v3 javascript. I am using the Geocoder feature where I am passing a city name and plotting it on the map. Along with this marker, I want to add a separate info window for every marker but I am not able to do that. All the infowindows are displaying the content that was set for the last marker instead of setting a different info window for each. Please find the javascript code below:
function initialize() {
geocoder = new google.maps.Geocoder();
var address = document.getElementById('address').value;
var jString = JSON.parse(address);
var infowindow;
for (var key in jString) {
contentStr = JSON.stringify(jString[key]); //This is step where I am setting the content which is independent for every maker
if (jString.hasOwnProperty(key)) {
geocoder.geocode( { 'address': key}, 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
});
infowindow = new google.maps.InfoWindow({
content: contentStr//Not able to access 'contentStr' set above.
});
infowindow.open(map,marker);
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
}
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);
}
google.maps.event.addDomListener(window, 'load', initialize);
After debugging I understood that for some reason, the value of the variable 'contentStr' being set during the last iteration of 'for' loop is only being used for all the below function calls made:
geocoder.geocode( { 'address': key}, function(results, status) {
So basically, I am not able to pass the variable 'contentStr' into the function defined in the argument of another function. I think I am missing something basic here. Could anyone please guide me about this?
Thank you!
I have had the same problem many times. Stolen from link below. You need to attach the infowindow to your marker.
Marker content (infoWindow) Google Maps
function createMarker(lat, lon, html) {
var newmarker = new google.maps.Marker({
position: new google.maps.LatLng(lat, lon),
map: map,
title: html
});
newmarker['infowindow'] = new google.maps.InfoWindow({
content: html
});
google.maps.event.addListener(newmarker, 'mouseover', function() {
this['infowindow'].open(map, this);
});
}
A second way of doing this. :
Google Maps API V3 infoWindow - All infoWindows displaying same content

Google Maps API custom Icons with SSL

I have a Google Maps Application and I want to put custom Icons instead of the generic red icon that usually shows up. But no matter what I do I can not set a different icon it always shows up as the red one. I read that you can not have https in the url for icons so I uploaded it to an image host but I still can't get the icon to change. How do I get a custom icon on the map or do I have to go with bing?
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(-34.397, 150.644);
var mapOptions = {
zoom: 10,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
}
function codeAddress() {
initialize();
var address = document.getElementById("address").value;
range = document.getElementById("distance").value;
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,
icon: "http://labs.google.com/ridefinder/images/mm_20_red.png"
position: results[0].geometry.location
});
lat1 = results[0].geometry.location.lat();
lng1 = results[0].geometry.location.lng();
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
load();
}
Notice where it says:
icon: "http://labs.google.com/ridefinder/images/mm_20_red.png"
Not matter what I change that too it always shows the red generic icon.
You can load marker images over both HTTP and HTTPS on your page. However, you will want to make sure that the scheme matches the containing page's scheme (or at least, make sure that you use HTTPS if the page does too).
It seems you have typo in your MarkerOptions object: a missing comma after the icon string.
var marker = new google.maps.Marker({
map: map,
icon: "http://labs.google.com/ridefinder/images/mm_20_red.png",
position: results[0].geometry.location
});

Google Maps Api v3 - Multiple Info Windows with custom content

I have finally managed to add multiple markers with custom icons to my Googlemap.
The next step would be to add an individual Infowindow for each marker.
Unfortunatelly i cant figure out how.
Here is my script so far:
<script type="text/javascript">
var offender_locations = [
["10010", "http://localhost/safenation/img/map_offender_icon.png"],
["10001", "http://localhost/safenation/img/map_visitor_icon.png"]
];
var myOptions = {zoom: 10,center: latlng,mapTypeId: google.maps.MapTypeId.ROADMAP};
var map = new google.maps.Map(document.getElementById("elementid"), myOptions);
var latlng = new google.maps.LatLng(0, 0);
var marker;
var i;
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 = 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
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(offender_locations[i][1]);
infowindow.open(map, marker);
}
})(marker, i));
} else {alert("The requested offender is not mappable !")};});
}
</script>
I think there now is a problem with the loop. When i try:
var icon = offender_locations[1][1];
all icons are "map_offender_icon.png"
When I use :
var icon = offender_locations[i][1];
nothing changes and all icons are still "map_offender_icon.png"
It seems the var offender_locations[i][1]; is not changing accordingly. The var offender_locations[i][0]; changes accordingly.
Your marker variable is local to your for loop which is not visible outside the loop so the statement
var infowindow = new google.maps.InfoWindow();
google.maps.event.addListener(marker, 'click', (function(marker, i)
is not able to set the listener for your marker.
Best way is include your Info window initialization inside your loop to set listeners to your entire markers.
Hope this helps.
The problem has been solved!
Working script:
Javascript Loop - 2nd variable Not Displaying
(Extracted from edit to the original question)

Categories