Google Maps API Finding Details - javascript

I am trying to use the google maps details about a location to display in an info window from a marker. I am creating a marker and want to get the address of that marker so that I can store it in a database. I am able to get the title of the marker but I do not know how to get the full address. This is my code:
<script>
let pos;
let map;
let bounds;
let infoWindow;
let currentInfoWindow;
let service;
let infoPane;
function initMap() {
bounds = new google.maps.LatLngBounds();
infoWindow = new google.maps.InfoWindow;
currentInfoWindow = infoWindow;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(position => {
pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
map = new google.maps.Map(document.getElementById('map'), {
center: pos,
zoom: 20
});
bounds.extend(pos);
infoWindow.setPosition(pos);
infoWindow.setContent('Location found.');
infoWindow.open(map);
map.setCenter(pos);
getNearbyPlaces(pos);
}, () => {
handleLocationError(true, infoWindow);
});
} else {
handleLocationError(false, infoWindow);
}
}
function handleLocationError(browserHasGeolocation, infoWindow) {
pos = { lat: -33.856, lng: 151.215 };
map = new google.maps.Map(document.getElementById('map'), {
center: pos,
zoom: 20
});
infoWindow.setPosition(pos);
infoWindow.setContent(browserHasGeolocation ?
'Geolocation permissions denied. Using default location.' :
'Error: Your browser doesn\'t support geolocation.');
infoWindow.open(map);
currentInfoWindow = infoWindow;
getNearbyPlaces(pos);
}
function getNearbyPlaces(position) {
let request = {
location: position,
rankBy: google.maps.places.RankBy.DISTANCE,
keyword: 'basketball courts'
};
service = new google.maps.places.PlacesService(map);
service.nearbySearch(request, nearbyCallback);
}
function nearbyCallback(results, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
createMarkers(results);
}
}
function createMarkers(places) {
places.forEach(place => {
let marker = new google.maps.Marker({
position: place.geometry.location,
map: map,
title: place.name
});
marker.addListener("click", () => {
map.setZoom(16);
map.setCenter(marker.getPosition());
});
bounds.extend(place.geometry.location);
});
map.fitBounds(bounds);
}
</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places&callback=initMap">
</script>
I am unfamiliar with javascript so I am not sure how exactly to format it. If it shows up in the infowindow I can work on it myself from there but if anyone has suggestions on how to show it there I would appreciate it.

To be fair you have done most of the work but if it is simply a case of taking the results from the nearbyPlaces search and adding to an infowindow then perhaps you can find use in the following. The work is done in the createMarkers function
<!doctype html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title>Google Maps: </title>
<style>
#map{
width:800px;
height:600px;
float:none;
margin:auto;
}
</style>
</head>
<body>
<div id='map'></div>
<script>
let pos;
let map;
let bounds;
let infoWindow;
let currentInfoWindow;
let service;
let infoPane;
function initMap() {
bounds = new google.maps.LatLngBounds();
infoWindow = new google.maps.InfoWindow;
currentInfoWindow = infoWindow;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(position => {
pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
map = new google.maps.Map(document.getElementById('map'), {
center: pos,
zoom: 20
});
bounds.extend(pos);
infoWindow.setPosition(pos);
infoWindow.setContent('Location found.');
infoWindow.open(map);
map.setCenter(pos);
getNearbyPlaces( pos );
}, () => {
handleLocationError(true, infoWindow);
});
} else {
handleLocationError(false, infoWindow);
}
}
function handleLocationError(browserHasGeolocation, infoWindow) {
pos = { lat: -33.856, lng: 151.215 };
map = new google.maps.Map(document.getElementById('map'), {
center: pos,
zoom: 20
});
infoWindow.setPosition(pos);
infoWindow.setContent(browserHasGeolocation ?
'Geolocation permissions denied. Using default location.' :
'Error: Your browser doesn\'t support geolocation.');
infoWindow.open(map);
currentInfoWindow = infoWindow;
getNearbyPlaces(pos);
}
function getNearbyPlaces(position) {
let request = {
location: position,
rankBy: google.maps.places.RankBy.DISTANCE,
keyword: 'basketball courts'
};
service = new google.maps.places.PlacesService(map);
service.nearbySearch(request, nearbyCallback);
}
function nearbyCallback(results, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
createMarkers(results);
}
}
function createMarkers(places) {
places.forEach(place => {
console.log(place)
let marker = new google.maps.Marker({
position: place.geometry.location,
map: map,
title:place.name,
/* assign the response data as a property of the marker */
content:place
});
/*
for convenience a regular anonymous function is better here
as it allws us to use `this` to refer to the marker itself
within the body of the function.
*/
marker.addListener("click", function(e){
map.setZoom(16);
map.setCenter( marker.getPosition() );
/*
Iterate through ALL properties ( or just some ) of the `this.contents`
property and set as the content for the infowindow
*/
infoWindow.setContent( Object.keys(this.content).map(k=>{
return [k,this.content[k] ].join('=')
}).join( String.fromCharCode(10) ) );
/* open the infowindow */
infoWindow.setPosition(e.latLng)
infoWindow.open(map,this);
});
bounds.extend(place.geometry.location);
});
map.fitBounds(bounds);
}
</script>
<script async defer src="//maps.googleapis.com/maps/api/js?key=<APIKEY>&libraries=places&callback=initMap">
</script>
</body>
</html>
The data returned is JSON and has a structure like this for each individual result. The location data contained therein will bear no resemblance to that found for others running this self same script but show suffice.
{
"business_status" : "OPERATIONAL",
"geometry" : {
"location" : {
"lat" : 52.7525688,
"lng" : 0.4036446
},
"viewport" : {
"northeast" : {
"lat" : 52.75354047989272,
"lng" : 0.4048724298927222
},
"southwest" : {
"lat" : 52.75084082010728,
"lng" : 0.4021727701072778
}
}
},
"icon" : "https://maps.gstatic.com/mapfiles/place_api/icons/v1/png_71/generic_business-71.png",
"icon_background_color" : "#7B9EB0",
"icon_mask_base_uri" : "https://maps.gstatic.com/mapfiles/place_api/icons/v2/generic_pinlet",
"name" : "Multi-Use Games Area",
"place_id" : "ChIJX2Y4mjyL10cRQ0885NSSeTE",
"plus_code" : {
"compound_code" : "QC33+2F King's Lynn",
"global_code" : "9F42QC33+2F"
},
"rating" : 0,
"reference" : "ChIJX2Y4mjyL10cRQ0885NSSeTE",
"scope" : "GOOGLE",
"types" : [ "point_of_interest", "establishment" ],
"user_ratings_total" : 0,
"vicinity" : "The Walks, nr, South St, King's Lynn"
}
Within the marker click callback function, where previously there is this:
infoWindow.setContent( Object.keys(this.content).map(k=>{
return [k,this.content[k] ].join('=')
}).join( String.fromCharCode(10) ) );
We can build up a string of whatever items you wish to use:
infoWindow.setContent( this.content.name ); // simply display the name
or
infoWindow.setContent(
`<h1>${this.content.name}</h1>
<p>${this.content.vicinity}</p>
<ul>
<li>Lat: ${this.content.geometry.location.lat()}</li>
<li>Lng: ${this.content.geometry.location.lng()}</li>
</ul>
<img src="${this.content.icon}" />`
); // show some HTML content

Related

How can I implement google map in the vue component?

I get reference from here : How to get the formatted address from a dragged marker in Google Version Maps
It using javascript
I want to implement it in the vue component
I try like this :
https://jsfiddle.net/oscar11/1krtvcfj/2/
I don't type code here. Because the code is too much. So you can directly see in jsfiddle
If I click geocode button, there exist error like this :
Uncaught ReferenceError: marker is not defined
How can I solve the error?
new Vue({
el: '#app',
template: `
<div>
<input id="address" type="textbox" value="Sydney, NSW">
<input type="button" value="Geocode" #click="codeAddress()">
</div>
`,
data() {
return {
geocoder: null,
map: null,
marker: null,
infowindow: null
}
},
mounted() {
this.infowindow = new google.maps.InfoWindow({
size: new google.maps.Size(150, 50)
})
google.maps.event.addDomListener(window, "load", this.initialize)
},
methods: {
initialize() {
this.geocoder = new google.maps.Geocoder();
let latlng = new google.maps.LatLng(-34.397, 150.644)
let mapOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
this.map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions)
google.maps.event.addListener(this.map, 'click', () => {
this.infowindow.close()
});
},
geocodePosition(pos) {
this.geocoder.geocode({
latLng: pos
}, responses => {
if (responses && responses.length > 0) {
this.marker.formatted_address = responses[0].formatted_address
} else {
this.marker.formatted_address = 'Cannot determine address at this location.'
}
this.infowindow.setContent(this.marker.formatted_address + "<br>coordinates: " + this.marker.getPosition().toUrlValue(6))
this.infowindow.open(this.map, this.marker)
});
},
codeAddress() {
let address = document.getElementById('address').value;
this.geocoder.geocode({
'address': address
}, (results, status) => {
if (status == google.maps.GeocoderStatus.OK) {
this.map.setCenter(results[0].geometry.location);
if (this.marker) {
this.marker.setMap(null);
if (this.infowindow) this.infowindow.close();
}
this.marker = new google.maps.Marker({
map: this.map,
draggable: true,
position: results[0].geometry.location
});
google.maps.event.addListener(this.marker, 'dragend', () => {
this.geocodePosition(this.marker.getPosition());
});
google.maps.event.addListener(this.marker, 'click', () => {
if (this.marker.formatted_address) {
this.infowindow.setContent(this.marker.formatted_address + "<br>coordinates: " + this.marker.getPosition().toUrlValue(6));
} else {
this.infowindow.setContent(address + "<br>coordinates: " + this.marker.getPosition().toUrlValue(6));
}
this.infowindow.open(this.map, this.marker);
});
google.maps.event.trigger(this.marker, 'click');
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
}
})
You should store globe value in the data of Vue component, and get the value by this.name in you methods.

let user get direction to specific location from his location in my website

I tried to combine this links with each other
"https://developers.google.com/maps/documentation/javascript/geolocation"
and
"https://developers.google.com/maps/documentation/javascript/examples/directions-panel"
but there is a problem with combining together by pushing user current location to a inner html of "div" and then get it back to push it into start of direction path
<script>
var infoWindow;
function initMap() {
var directionsDisplay = new google.maps.DirectionsRenderer;
var directionsService = new google.maps.DirectionsService;
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 18,
center: { lat: 30.0879217, lng: 31.3439407 }
});
infoWindow = new google.maps.InfoWindow;
// Try HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
document.getElementById("position1").innerHTML=position.coords.latitude;
document.getElementById("position2").innerHTML=position.coords.longitude;
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
infoWindow.setPosition(pos);
infoWindow.setContent('Location found.');
infoWindow.open(map);
map.setCenter(pos);
}, function() {
handleLocationError(true, infoWindow, map.getCenter());
});
}
directionsDisplay.setMap(map);
calculateAndDisplayRoute(directionsService, directionsDisplay);
document.getElementById('mode').addEventListener('change', function () {
calculateAndDisplayRoute(directionsService, directionsDisplay);
});
}
function calculateAndDisplayRoute(directionsService, directionsDisplay) {
var selectedMode = document.getElementById('mode').value;
var x=document.getElementById("position1").innerHTML;
var y=document.getElementById("position2").innerHTML;
directionsService.route({
origin: { lat: 30.0879217, lng: 31.3439407 }, // Haight.
destination: { lat: Number(x), lng: Number(y) }, // Ocean Beach.
// Note that Javascript allows us to access the constant
// using square brackets and a string value as its
// "property."
travelMode: google.maps.TravelMode[selectedMode]
}, function (response, status) {
if (status == 'OK') {
directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCb0QRzb5LcbAkUbRH3kRDv4WNVDRMBeq4&callback=initMap">
</script>
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Travel modes in directions</title>
<style>
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
#floating-panel {
position: absolute;
top: 10px;
left: 25%;
z-index: 5;
background-color: #fff;
padding: 5px;
border: 1px solid #999;
text-align: center;
font-family: 'Roboto', 'sans-serif';
line-height: 30px;
padding-left: 10px;
}
</style>
</head>
<body>
<div id="position1" ></div>
<div id="position2"></div>
<div id="floating-panel">
<b>Mode of Travel: </b>
<select id="mode">
<option value="DRIVING">Driving</option>
<option value="WALKING">Walking</option>
<option value="BICYCLING">Bicycling</option>
<option value="TRANSIT">Transit</option>
</select>
</div>
<div id="map"></div>
You can try something like this:
<script>
var infoWindow;
function initMap() {
// Try HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
document.getElementById("position1").innerHTML=position.coords.latitude;
document.getElementById("position2").innerHTML=position.coords.longitude;
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
var directionsDisplay = new google.maps.DirectionsRenderer;
var directionsService = new google.maps.DirectionsService;
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 18,
center: { lat: 30.0879217, lng: 31.3439407 }
});
infoWindow = new google.maps.InfoWindow;
infoWindow.setPosition(pos);
infoWindow.setContent('Location found.');
infoWindow.open(map);
map.setCenter(pos);
directionsDisplay.setMap(map);
calculateAndDisplayRoute(directionsService, directionsDisplay);
document.getElementById('mode').addEventListener('change', function () {
calculateAndDisplayRoute(directionsService, directionsDisplay);
});
}, function() {
handleLocationError(true, infoWindow, map.getCenter());
});
}
}
function calculateAndDisplayRoute(directionsService, directionsDisplay) {
var selectedMode = document.getElementById('mode').value;
var x=document.getElementById("position1").innerHTML;
var y=document.getElementById("position2").innerHTML;
directionsService.route({
origin: { lat: 30.0879217, lng: 31.3439407 }, // Haight.
destination: { lat: Number(x), lng: Number(y) }, // Ocean Beach.
// Note that Javascript allows us to access the constant
// using square brackets and a string value as its
// "property."
travelMode: google.maps.TravelMode[selectedMode]
}, function (response, status) {
if (status == 'OK') {
directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCb0QRzb5LcbAkUbRH3kRDv4WNVDRMBeq4&callback=initMap">
</script>
Your code crash because you tried to read your position in the calculateAndDisplayRoute before the browser calls your callback where you initialize the lat and long HTML's objects.
Tell me if you have some questions or comments.

Google map api open tab with route from geolocation to placeId

I would like to create a link that open a new google map tab with route from navigator.geolocation.getCurrentPosition to a specific placeId.
If there is geolocation a problem then, open a new tab without origin completed
Here is what I try:
const options = {
placeId: 'ChIJDyx4bNhu5kcRqJ3RkAPGMEk',
latitude: 48.925606,
longitude: 2.327621,
};
const mapOptions = {
zoom: 15,
center: new google.maps.LatLng(options.latitude, options.longitude),
};
const map = new google.maps.Map(document.getElementById('Map'), mapOptions);
const service = new google.maps.places.PlacesService(map);
service.getDetails({
placeId: options.placeId,
}, (result, status) => {
if (status !== google.maps.places.PlacesServiceStatus.OK) {
alert(status);
return;
}
const marker = new google.maps.Marker({
map: map,
position: result.geometry.location,
});
});
$('.js-ItinaryFromI').on('click', () => {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition((position) => {
const pos = {
lat: position.coords.latitude,
lng: position.coords.longitude,
};
}, () => {
// The problem seems to come from this line :
window.open(`https://www.google.com/maps/dir/origin=pos&destination=place_id:${options.placeId}&travelmode=driving`, '_blank');
});
} else {
// And this line
window.open(`https://www.google.com/maps/dir//place_id${options.placeId}&travelmode=driving`, '_blank');
}
});
Any idea please ?
You should use Google Maps Directions API if you wanted to calculate directions between location. You can search for directions for several modes of transportation, including transit, driving, walking, or cycling.
These parameters (origin, destination, travel_mode) are used in Google Maps Directions API and probably won't work well using Google Maps.
I also noticed in the code you provided that certain variables were not properly concatenated into the request. Hence, your request would not provide accurate results.
Here's a sample of valid request:
window.open('https://maps.googleapis.com/maps/api/directions/json?origin='+pos.lat+','+pos.lng+'&destination=place_id:'+options.placeId+'&travelmode=driving&key=YOUR_API_KEY', '_blank');
Don't forget to include your API key in each request.
I modified your code a bit. You can check it below:
const options = {
placeId: 'ChIJDyx4bNhu5kcRqJ3RkAPGMEk',
//placeId: 'ChIJ51Ic7BXIlzMRK2WH8qoM6Ek',
latitude: 48.925606,
longitude: 2.327621,
};
function initMap() {
const mapOptions = {
zoom: 15,
center: new google.maps.LatLng(options.latitude, options.longitude),
};
const map = new google.maps.Map(document.getElementById('Map'), mapOptions);
const service = new google.maps.places.PlacesService(map);
service.getDetails({
placeId: options.placeId,
}, (result, status) => {
if (status !== google.maps.places.PlacesServiceStatus.OK) {
alert(status);
return;
}
const marker = new google.maps.Marker({
map: map,
position: result.geometry.location,
});
});
if ( navigator.geolocation ) {
navigator.geolocation.getCurrentPosition((position) => {
const pos = {
lat: position.coords.latitude,
lng: position.coords.longitude,
};
document.getElementById('js-ItinaryFromI').addEventListener('click', () => {
window.open('https://maps.googleapis.com/maps/api/directions/json?origin='+pos.lat+','+pos.lng+'&destination=place_id:'+options.placeId+'&travelmode=driving&key=[API-KEY]', '_blank');
});
});
} else {
alert('Geolocation not found!');
}
}
html,body,#Map {
width:100%;
height:100%;
}
<button id="js-ItinaryFromI">Click Me</button>
<div id="Map" ></div>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCzjs-bUR6iIl8yGLr60p6-zbdFtRpuXTQ&callback=initMap&libraries=places">
</script>
You can try this using JSBin. For some reason it doesn't work here in Stackoverflow's code snippet. I don't know why.
Good luck and happy coding!

Meteor implementing Google Maps and Google Places

I'm attempting to implement a Google Map on my Meteor app that will get the user's location and then will find places that serve food near the user. I began by implementing the example
given by Google, and it worked fine when I did it that way; however I'm trying to implement it properly by adding it to the actual Javascript file and it is now giving me a "Google is undefined" error.
menuList = new Mongo.Collection('items');
if (Meteor.isClient) {
var pls;
var map;
var infowindow;
Meteor.startup(function () {
//get user location and return location in console
var options = {
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0
};
function success(pos) {
var crd = pos.coords;
console.log('Your current position is:');
console.log('Latitude : ' + crd.latitude);
console.log('Longitude: ' + crd.longitude);
console.log('More or less ' + crd.accuracy + ' meters.');
pls = {lat: crd.latitude, lng: crd.longitude};
};
function error(err) {
console.warn('ERROR(' + err.code + '): ' + err.message);
};
navigator.geolocation.getCurrentPosition(success, error, options);
})
Meteor.methods({
callback: function (results, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
}
},
createMarker: function (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);
});
}
})
Template.searchIt.helpers({
'initMap': function () {
console.log("HERE");
//Dummy values I placed for StackOverflow
var pyrmont = {lat: -33.234, lng: 95.343};
map = new google.maps.Map(document.getElementById('map'), {
center: pyrmont,
zoom: 15
});
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.nearbySearch({
location: pyrmont,
radius: 500,
types: ['food']
}, callback);
}
})
}
<head>
<title>Place searches</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<div id="map"></div>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyACgaDFJrh2pMm-bSta1S40wpKDDSpXO2M
&signed_in=true&libraries=places" async defer></script>
<style>
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
}
</style>
</head>
<body>
{{>searchIt}}
</body>
<template name="searchIt">
{{initMap}}
</template>
You should try the dburles:google-maps package.
Here is an example written by its author: http://meteorcapture.com/how-to-create-a-reactive-google-map/
Have fun!
i had to place the code you have above inside of a GoogleMaps.ready('map', callback) block. or inside of an if (GoogleMaps.loaded()) {} block...
for instance.. this works just fine:
caveat: i'm using the radarSearch, but the concept is the same.
Template.galleryCard.onRendered(function() {
GoogleMaps.ready('minimap', function(map) {
const params = {
map: map,
name: 'The Spice Suite',
loc: {lat: 38.9738619, lng: -77.01829699999999},
};
const service = new google.maps.places.PlacesService(params.map.instance);
let request2 = {
//name & location & radius (meters).
name: params.name,
location: params.loc,
radius: 100,
};
let callback = function(results,status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
console.log(results[0]);
return results[0].place_id;
} else {
console.log(status);
}
};
service.radarSearch(request2,callback);
});
});

Multiple markers on google maps using json and placeid

the problem i've got is that I don't know where the problem is :P
From the beginning. I've got 3 files, the json file JS and html. JS should get placeid from json and based on that place a marker on the map. It's all pretty simple but somehow it doesn't work, the map is being created but no markers show up.
Here're the files:
JSON:
[{ "placeid": 'ChIJu6HrLMVWIkcRWHTA90kiueI' , "content": " 1 " } ,
{ "placeid": 'ChIJnXBuJ34zGUcRvt9FTKrPeeM' , "content": " 2 " } ,
{ "placeid": 'ChIJiwUNhqX7PEcRdJjYqzrWYjs' , "content": " 3 " } ]
HTML:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script src="http://code.jquery.com/jquery-migrate-1.1.1.min.js"></script>
<script src="functions_edit.js"></script>
</head>
<body>
<div id="map-canvas" style="width:500px; height:400px"></div>
</body>
</html>
JS:
var openedInfoWindow = null;
function initialize() {
var latitude = 51.9315631,
longitude = 19.473451,
radius = 8000,
center = new google.maps.LatLng(latitude,longitude),
mapOptions = {
center: center,
zoom: 5,
mapTypeId: google.maps.MapTypeId.ROADMAP,
scrollwheel: false
};
var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
setMarkers(center, radius, map);
}
function setMarkers(center, radius, map) {
var json = (function () {
var json = null;
$.ajax({
'async': false,
'global': false,
'url': "placeid.json",
'dataType': "json",
'success': function (data) {
json = data;
}
});
return json;
})();
for (var i = 0, length = json.length; i < length; i++) {
var data = json[i];
var service = new google.maps.places.PlacesService(map);
service.getDetails({
placeId: data.placeid
}, function (result, status) {
if (status != google.maps.places.PlacesServiceStatus.OK) {
alert(status);
return;
}
var marker = new google.maps.Marker({
map: map,
place: {
placeId: data.placeid,
location: result.geometry.location
}
//position: result.geometry.location
});
});
infoBox(map, marker, data);
}
}
function infoBox(map, marker, data) {
var infoWindow = new google.maps.InfoWindow();
google.maps.event.addListener(marker, "click", function(e) {
infoWindow.setContent(data.content);
infoWindow.open(map, marker);
});
(function(marker, data) {
google.maps.event.addListener(marker, "click", function(e) {
infoWindow.setContent(data.content);
infoWindow.open(map, marker);
});
})(marker, data);
}
google.maps.event.addDomListener(window, 'load', initialize);
With the posted code I get a javascript error: Uncaught ReferenceError: marker is not defined
You are calling the InfoBox function in the wrong place (outside the scope where marker exists).
Once I fix that I get infowindows, but you have an issue that can be solved by function closure (all the infowindows have the content "3", the last marker processed). (For an example of function closure see Google Maps JS API v3 - Simple Multiple Marker Example)
working fiddle
code snippet:
var placeid_json = [{
"placeid": 'ChIJu6HrLMVWIkcRWHTA90kiueI',
"content": " 1 "
}, {
"placeid": 'ChIJnXBuJ34zGUcRvt9FTKrPeeM',
"content": " 2 "
}, {
"placeid": 'ChIJiwUNhqX7PEcRdJjYqzrWYjs',
"content": " 3 "
}];
var openedInfoWindow = null;
function initialize() {
var latitude = 51.9315631,
longitude = 19.473451,
radius = 8000,
center = new google.maps.LatLng(latitude, longitude),
mapOptions = {
center: center,
zoom: 5,
mapTypeId: google.maps.MapTypeId.ROADMAP,
scrollwheel: false
};
var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
setMarkers(center, radius, map);
}
function setMarkers(center, radius, map) {
/* var json = (function () {
var json = null;
$.ajax({
'async': false,
'global': false,
'url': "placeid.json",
'dataType': "json",
'success': function (data) {
json = data;
}
});
return json;
})(); */
var json = placeid_json;
for (var i = 0, length = json.length; i < length; i++) {
var data = json[i];
createMarker(data, map);
}
}
function createMarker(data, map) {
var service = new google.maps.places.PlacesService(map);
service.getDetails({
placeId: data.placeid
}, function (result, status) {
if (status != google.maps.places.PlacesServiceStatus.OK) {
alert(status);
return;
}
var marker = new google.maps.Marker({
map: map,
place: {
placeId: data.placeid,
location: result.geometry.location
}
//position: result.geometry.location
});
infoBox(map, marker, data, result);
});
}
function infoBox(map, marker, data, result) {
var infoWindow = new google.maps.InfoWindow();
google.maps.event.addListener(marker, "click", function (e) {
infoWindow.setContent(data.content);
infoWindow.open(map, marker);
});
(function (marker, data) {
google.maps.event.addListener(marker, "click", function (e) {
infoWindow.setContent(data.content+"<br>"+result.name);
infoWindow.open(map, marker);
});
})(marker, data);
}
google.maps.event.addDomListener(window, 'load', initialize);
<script src="https://maps.googleapis.com/maps/api/js?libraries=places&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="map-canvas" style="width:500px; height:400px"></div>

Categories