setCenter in google map api is not working. map is invisible - google-maps

I have been working on Google map project and encountered this issue.
I wanted to use setCenter method to relocate map center. I only can see the gray map instead. I think it's supposed to be working find but I don't know what is wrong
Here is how it looks likeenter image description here
enter code here
var map;
var marker;
function initMap(){
var options = {
center: new google.maps.LatLng(37.4989885,127.03282719999993),
zoom : 8
};
map = new google.maps.Map(document.getElementById('map'), options);
marker = new google.maps.Marker({
position : {lat:37.4989885,lng:127.03282719999993},
map : map
});
}
function changePosition(altitude, longitude){
map.setCenter(new google.maps.LatLng(altitude,longitude));
marker.setPosition(new google.maps.LatLng(altitude,longitude));
}
$(function() {
var url = "tourXML";
$.ajax({
type : "GET",
url : url,
dataType : "text",
success : function(data) {
var temp = $.trim(data);
obj = JSON.parse(temp);
var longitude = parseFloat(obj.longitude);
var altitude = parseFloat(obj.altitude);
changePosition(altitude, longitude);
$("#altitude").html(obj.altitude);
$("#longitude").html(obj.longitude);
},
error : function() {
alert("error.");
}
});
});

You can use this code Modified it as per you need
map.setCenter(21.219381 ,72.840128);
or
map.setCenter(pos);
enter code here
function initMap ()
{
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 5,
center: {lat: 21.219381, lng: 72.840128}
});
var geocoder = new google.maps.Geocoder;
var trafficLayer = new google.maps.TrafficLayer();
trafficLayer.setMap(map);
var infowindow = new google.maps.InfoWindow;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
geocoder.geocode({'location': pos}, function(results, status) {
if (status === 'OK') {
if (results[0]) {
console.log(JSON.stringify(results[0]));
map.setZoom(11);
var marker = new google.maps.Marker({
position: pos,
map: map
});
infowindow.setContent(results[0].formatted_address);
infowindow.open(map, marker);
map.setCenter(pos);
} else {
window.alert('No results found');
}
} else {
window.alert('Geocoder failed due to: ' + status);
}
});
}, function() {
handleLocationError(true, infoWindow, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
}
}

Related

Google maps reverse geocoding returns zero_results

I have this code where I try getting address from coords in a google map,but my phone returns status error zero_results.
I am sure my location is available because if I tested via browser and my address location for coordinates is returned.
Any ideas?
<!DOCTYPE html>
<html>
<head>
<title>Geolocation test</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style type="text/css">
div#mapdiv {
width: 500px;
height: 300px;
margin: 10px auto;
}
</style>
</head>
<body onload="">
<div id="mapdiv"></div>
<div id="msg"></div>
<div id="msg2"></div>
<script type="text/javascript">
function initMap() {
var pos2;
var map = new google.maps.Map(document.getElementById('mapdiv'), {
center: {lat: -34.397, lng: 150.644},
zoom: 12
});
var infoWindow = new google.maps.InfoWindow({map: map});
var latLng;
// Try HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
pos2 = pos;
latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
infoWindow.setPosition(pos);
infoWindow.setContent('La tua posizione.');
map.setCenter(pos);
}, function () {
handleLocationError(true, infoWindow, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
}
var geocoder = new google.maps.Geocoder;
geocoder.geocode({'latLng': pos2}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
map.setZoom(11);
var marker = new google.maps.Marker({
position: pos2,
map: map
});
document.getElementById('msg').innerHTML = results[0].formatted_address;
} else {
document.getElementById('msg').innerHTML = 'results[1].formatted_address';
window.alert('No results found');
}
} else {
document.getElementById('msg2').innerHTML = JSON.stringify(pos2);
window.alert('Geocoder failed due to: ' + status);
}
});
}
function handleLocationError(browserHasGeolocation, infoWindow, pos) {
infoWindow.setPosition(pos);
infoWindow.setContent(browserHasGeolocation ?
'Error: The Geolocation service failed.' :
'Error: Your browser doesn\'t support geolocation.');
}
</script>
<script async defer
src="http://maps.google.com/maps/api/js?key=API_KEY&callback=initMap"></script>
</body>
</html>
`
the geolocation service is asynchronous, you need to use the data (pos2) in the callback function when/where it is available. Currently you are calling the geocoder before that value is set.
proof of concept fiddle
// Try HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
pos2 = pos;
latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
map.setCenter(pos);
infoWindow.setPosition(pos);
infoWindow.setContent('La tua posizione.');
// call reverse geocoder with location returned by geolocation service
var geocoder = new google.maps.Geocoder;
geocoder.geocode({
'latLng': pos2
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
map.setZoom(11);
var marker = new google.maps.Marker({
position: pos2,
map: map
});
infoWindow.setContent('La tua posizione.<br>'+ results[0].formatted_address);
} else {
document.getElementById('msg').innerHTML = 'results[1].formatted_address';
window.alert('No results found');
}
} else {
document.getElementById('msg2').innerHTML = JSON.stringify(pos2);
window.alert('Geocoder failed due to: ' + status);
}
});
map.setCenter(pos);
}, function() {
handleLocationError(true, infoWindow, map.getCenter());
});
code snippet:
div#mapdiv {
width: 500px;
height: 300px;
margin: 10px auto;
}
<div id="mapdiv"></div>
<div id="msg"></div>
<div id="msg2"></div>
<script type="text/javascript">
function initMap() {
var pos2;
var map = new google.maps.Map(document.getElementById('mapdiv'), {
center: {
lat: -34.397,
lng: 150.644
},
zoom: 12
});
var infoWindow = new google.maps.InfoWindow({
map: map
});
var latLng;
// Try HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
pos2 = pos;
latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
map.setCenter(pos);
infoWindow.setPosition(pos);
infoWindow.setContent('La tua posizione.');
var geocoder = new google.maps.Geocoder;
geocoder.geocode({
'latLng': pos2
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
map.setZoom(11);
var marker = new google.maps.Marker({
position: pos2,
map: map
});
infoWindow.setContent('La tua posizione.<br>'+ results[0].formatted_address);
} else {
document.getElementById('msg').innerHTML = 'results[1].formatted_address';
window.alert('No results found');
}
} else {
document.getElementById('msg2').innerHTML = JSON.stringify(pos2);
window.alert('Geocoder failed due to: ' + status);
}
});
map.setCenter(pos);
}, function() {
handleLocationError(true, infoWindow, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
}
}
function handleLocationError(browserHasGeolocation, infoWindow, pos) {
infoWindow.setPosition(pos);
infoWindow.setContent(browserHasGeolocation ?
'Error: The Geolocation service failed.' :
'Error: Your browser doesn\'t support geolocation.');
}
</script>
<script async defer src="https://maps.google.com/maps/api/js?callback=initMap"></script>

Google API to map nearby properties in Salesforce

I asked this question originally in the Salesforce StackExchange, but was redirected here, since it's more of a Google API question than a Salesforce question.
Right now I have the following code, which creates a marker at the location of the property on a visualforce page that has an embedded Google Map. When the user clicks on the marker, an info window appears with information on the property.
<apex:page standardController="Property__c">
<head>
<script type="text/javascript" src="https://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var myOptions = {
zoom: 18,
mapTypeId: google.maps.MapTypeId.HYBRID,
mapTypeControl: true,
scrollwheel: false
}
var map;
var marker;
var geocoder = new google.maps.Geocoder();
var address = "{!Property__c.Property_Address__c}, " + "{!Property__c.City__c}, " + "{!Property__c.State__c} " + "{!Property__c.Zip_Postal_Code__c}}";
var infowindow = new google.maps.InfoWindow({
content: "<b>{!Property__c.Name}</b><br>{!Property__c.Property_Address__c}<br>{!Property__c.City__c}, {!Property__c.State__c} {!Property__c.Zip_Postal_Code__c}"
});
geocoder.geocode({
address: address
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK && results.length) {
if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
//create map
map = new google.maps.Map(document.getElementById("map"), myOptions);
map.setTilt(45);
//center map
map.setCenter(results[0].geometry.location);
//create marker
marker = new google.maps.Marker({
position: results[0].geometry.location,
map: map,
title: "{!Property__c.Name}"
});
//add listeners
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map, marker);
});
google.maps.event.addListener(infowindow, 'closeclick', function() {
map.setCenter(marker.getPosition());
});
}
} else {
$('#map').css({
'height': '15px'
});
$('#map').html("Oops! {!Property__c.Name}'s billing address could not be found, please make sure the address is correct.");
resizeIframe();
}
});
function resizeIframe() {
var me = window.name;
if (me) {
var iframes = parent.document.getElementsByName(me);
if (iframes && iframes.length == 1) {
height = document.body.offsetHeight;
iframes[0].style.height = height + "px";
}
}
}
});
</script>
<style>
#map {
font-family: Arial;
font-size: 12px;
line-height: normal !important;
height: 800px;
background: transparent;
}
</style>
</head>
<body>
<div id="map"></div>
</body>
</apex:page>
This is working just fine. But I am trying to modify it to also show properties nearby to this property. I have gotten as far as using an SOQL query to find these properties, pass their addresses into an array, geocode these addresses and set a marker at each geocoordinate. All of that works just swell.
Where I've been stuck, is in displaying the infowindow that appears when the user clicks one of these markers. Not only can I not create an infowindow for the NEW markers, but the infowindow for the OLD "main" marker is breaking as well. In fact, even if I comment the infowindow and listener events for the new markers, the original is still broken. These infowindows need to display different information than the infowindow for the "main" marker. Here is my modified code:
$(document).ready(function() {
var myOptions = {
zoom: 18,
mapTypeId: google.maps.MapTypeId.HYBRID,
mapTypeControl: true,
scrollwheel: false
}
var map;
var marker;
var marker2;
var geocoder = new google.maps.Geocoder();
var address = "{!Property__c.Property_Address__c}, " + "{!Property__c.City__c}, " + "{!Property__c.State__c} " + "{!Property__c.Zip_Postal_Code__c}}";
var infowindow = new google.maps.InfoWindow({
content: "<b>{!Property__c.Name}</b><br>{!Property__c.Property_Address__c}<br>{!Property__c.City__c}, {!Property__c.State__c} {!Property__c.Zip_Postal_Code__c}"
});
geocoder.geocode({
address: address
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK && results.length) {
if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
//create map
map = new google.maps.Map(document.getElementById("map"), myOptions);
map.setTilt(45);
//center map
map.setCenter(results[0].geometry.location);
//create marker
marker = new google.maps.Marker({
position: results[0].geometry.location,
map: map,
title: "{!Property__c.Name}"
});
//add listeners
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map, marker);
});
google.maps.event.addListener(infowindow, 'closeclick', function() {
map.setCenter(marker.getPosition());
});
//several markers
//Get Geos
var geos = [];
var idy = 0; <
apex: repeat value = "{!getgeoList}"
var = "m" >
geos[idy++] = "{!m}"; <
/apex:repeat>
for (var i = 0; i < geos.length; ++i) {
console.log('geo' + geos[i] + 'out of' + geos.length);
geocodeAddress(geos[i]);
}
function geocodeAddress(location) {
geocoder.geocode({
'address': location
}, function(results, status) {
// alert(status);
if (status == google.maps.GeocoderStatus.OK) {
// alert(results[0].geometry.location+location);
createMarker(results[0].geometry.location, location);
} else {
alert("some problem in geocode" + status);
}
});
}
function createMarker(latlng, html) {
marker2 = new google.maps.Marker({
position: latlng,
map: map
});
addIinfo(marker2, html);
}
function addInfo(marker2, html) {
var infowindow2 = new google.maps.InfoWindow({
content: html
});
marker2.addListener(marker2, 'click', function() {
infowindow2.open(marker2.get('map'), marker2);
});
}
}
} else {
$('#map').css({
'height': '15px'
});
$('#map').html("Oops! {!Property__c.Name}'s billing address could not be found, please make sure the address is correct.");
resizeIframe();
}
});
function resizeIframe() {
var me = window.name;
if (me) {
var iframes = parent.document.getElementsByName(me);
if (iframes && iframes.length == 1) {
height = document.body.offsetHeight;
iframes[0].style.height = height + "px";
}
}
}
});
I changed marker2.addListener to google.maps.event.addListener. This worked, except that my original marker was showing the same information as the marker2 markers. When I changed the marker2 icon to blue, I realized that this was because it was putting a marker2 marker over the original marker. So I changed i = 0 to i=1 in my for loop, and now my code works just great! :)
Here is my new code:
$(document).ready(function() {
var myOptions = {
zoom: 18,
mapTypeId: google.maps.MapTypeId.HYBRID,
mapTypeControl: true,
scrollwheel: false
}
var map;
var marker;
var marker2;
var geocoder = new google.maps.Geocoder();
var address = "{!Property__c.Property_Address__c}, " + "{!Property__c.City__c}, " + "{!Property__c.State__c} " + "{!Property__c.Zip_Postal_Code__c}}";
var infowindow = new google.maps.InfoWindow({
content: "<b>{!Property__c.Name}</b><br>{!Property__c.Property_Address__c}<br>{!Property__c.City__c}, {!Property__c.State__c} {!Property__c.Zip_Postal_Code__c}"
});
geocoder.geocode({
address: address
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK && results.length) {
if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
//create map
map = new google.maps.Map(document.getElementById("map"), myOptions);
map.setTilt(45);
//center map
map.setCenter(results[0].geometry.location);
//create marker
marker = new google.maps.Marker({
position: results[0].geometry.location,
map: map,
title: "{!Property__c.Name}"
});
//add listeners
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map, marker);
});
google.maps.event.addListener(infowindow, 'closeclick', function() {
map.setCenter(marker.getPosition());
});
//several markers
//Get Geos
var geos = [];
var idy=0;
<apex:repeat value="{!getgeoList}" var="m">
geos[idy++]="{!m}";
</apex:repeat>
for (var i = 1; i < geos.length; ++i) {
console.log('geo' + geos[i] + 'out of' + geos.length);
geocodeAddress(geos[i]);
}
function geocodeAddress(location) {
geocoder.geocode({
'address': location
}, function(results, status) {
// alert(status);
if (status == google.maps.GeocoderStatus.OK) {
// alert(results[0].geometry.location+location);
createMarker(results[0].geometry.location, location);
} else {
alert("some problem in geocode" + status);
}
});
}
function createMarker(latlng, html) {
marker2 = new google.maps.Marker({
position: latlng,
map: map,
icon:'http://maps.google.com/mapfiles/ms/icons/blue-dot.png'
});
addInfo(marker2,html);
}
function addInfo(marker2,html) {
var infowindow2 = new google.maps.InfoWindow({
content: html });
google.maps.event.addListener(marker2, 'click', function() {
infowindow2.open(map, marker2);
});
}
}
} else {
$('#map').css({
'height': '15px'
});
$('#map').html("Oops! {!Property__c.Name}'s billing address could not be found, please make sure the address is correct.");
resizeIframe();
}
});
function resizeIframe() {
var me = window.name;
if (me) {
var iframes = parent.document.getElementsByName(me);
if (iframes && iframes.length == 1) {
height = document.body.offsetHeight;
iframes[0].style.height = height + "px";
}
}
}
});

Issue to set map in center so multiple marker display

i am using ionic framework. i created map and multiple markers and value came from server side.all data came properly but i don't know why i getting this error-
ionic.bundle.js:25642 TypeError: Cannot read property 'fitBounds' of null
at autoCenter (app.js:147)
at app.js:135
at processQueue (ionic.bundle.js:27879)
at ionic.bundle.js:27895
at Scope.$eval (ionic.bundle.js:29158)
at Scope.$digest (ionic.bundle.js:28969)
at Scope.$apply (ionic.bundle.js:29263)
at done (ionic.bundle.js:23676)
at completeRequest (ionic.bundle.js:23848)
at XMLHttpRequest.requestLoaded (ionic.bundle.js:23789)
code :
angular.module('starter', ['ionic', 'ngCordova'])
.run(function ($ionicPlatform, GoogleMaps) {
$ionicPlatform.ready(function() {
if(window.cordova && window.cordova.plugins.Keyboard) {
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
// Don't remove this line unless you know what you are doing. It stops the viewport
// from snapping when text inputs are focused. Ionic handles this internally for
// a much nicer keyboard experience.
cordova.plugins.Keyboard.disableScroll(true);
}
if(window.StatusBar) {
StatusBar.styleDefault();
}
GoogleMaps.init();
});
})
.config(function ($stateProvider, $urlRouterProvider) {
$stateProvider
.state('map', {
url: '/',
templateUrl: 'templates/map.html',
controller: 'MapCtrl'
});
$urlRouterProvider.otherwise("/");
})
.factory('Markers', function ($http) {
var markers = [];
return {
getMarkers: function () {
return $http.get("http://localhost:8080/LocationServices/markers.php").then(function (response) {
markers = response;
return markers;
});
}
}
})
.factory('GoogleMaps', function ($cordovaGeolocation, Markers) {
var apiKey = false;
var map = null;
var zoomVal = 15
function initMap() {
var options = { timeout: 10000, enableHighAccuracy: true };
$cordovaGeolocation.getCurrentPosition(options).then(function (position) {
var latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
console.log("Latitude current: ", position.coords.latitude);
console.log("Longitude current: ", position.coords.longitude);
var mapOptions = {
center: latLng,
zoom: zoomVal,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map"), mapOptions);
//Wait until the map is loaded
google.maps.event.addListenerOnce(map, 'idle', function () {
var marker = new google.maps.Marker({
map: map,
animation: google.maps.Animation.DROP,
position: latLng
});
//Load the markers
loadMarkers(map);
//map.setCenter(new google.maps.LatLng(-37.92, 151.25));
});
}, function (error) {
console.log("Could not get location");
//Load the markers
loadMarkers(map);
//map.setCenter(new google.maps.LatLng(-37.92, 151.25));
});
}
function loadMarkers(map) {
//Get all of the markers from our Markers factory
Markers.getMarkers().then(function (markers) {
console.log("Markers: ", markers);
var markersss = new Array();
var records = markers.data.markers;
for (var i = 0; i < records.length; i++) {
var record = records[i];
console.log("Latitude: ", record.lat);
console.log("Longitude: ", record.lng);
var markerPos = new google.maps.LatLng(record.lat, record.lng);
console.log("marker position", "" + markerPos);
// Add the markerto the map
var marker = new google.maps.Marker({
map: map,
animation: google.maps.Animation.DROP,
position: markerPos
});
markersss.push(marker);
var infoWindowContent = "<h4>" + record.name + "</h4>";
addInfoWindow(marker, infoWindowContent, record);
}
autoCenter(map, markersss);
});
}
function autoCenter(map1, markersss) {
//Create a new viewpoint bound
var bounds = new google.maps.LatLngBounds();
//Go through each...
for (var i = 0; i < markersss.length; i++) {
bounds.extend(markersss[i].position);
console.log("bounds position", "" + markersss[i].position);
}
//Fit these bounds to the map
map1.fitBounds(bounds);
map1.setCenter(bounds.getCenter());
//remove one zoom level to ensure no marker is on the edge.
map1.setZoom(vm.googleMap.getZoom() - 1);
// set a minimum zoom
// if you got only 1 marker or all markers are on the same address map will be zoomed too much.
if (map1.getZoom() > zoomVal) {
map1.setZoom(zoomVal);
}
}
function addInfoWindow(marker, message, record) {
var infoWindow = new google.maps.InfoWindow({
content: message
});
google.maps.event.addListener(marker, 'click', function () {
infoWindow.open(map, marker);
});
}
return {
init: function () {
initMap();
}
}
})
.controller('MapCtrl', function ($scope, $state, $cordovaGeolocation) {
});
The map will only be created when $cordovaGeolocation.getCurrentPosition was successfull, but you also call loadMarkers when it wasn't successfull(map is null in this case)
Solution: create the map outside of the getCurrentPosition-callbacks (with a default-value for center).
In the success-callback create the marker and set the center of the map
function initMap() {
var options = { timeout: 10000, enableHighAccuracy: true },
mapOptions = {
center: new google.maps.LatLng(-37.92,151.25),
zoom: zoomVal,
mapTypeId: google.maps.MapTypeId.ROADMAP
},
map = new google.maps.Map(document.getElementById("map"), mapOptions);
google.maps.event.addListenerOnce(map, 'idle', function () {
$cordovaGeolocation.getCurrentPosition(options).then(function (position) {
var center = new google.maps.LatLng( position.coords.latitude,
position.coords.longitude);
map.setCenter(center);
new google.maps.Marker({
map : map,
animation : google.maps.Animation.DROP,
position : center
});
loadMarkers(map);
}, function (error) {
loadMarkers(map);
});
});
}

Google Places API - Adding Places Details

I have the following code:
function getLocation()
{
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(start,showError);
}
else{
error('Geo Location is not supported');
}
}
function start(position) {
var mySearch = document.getElementById("search").value;
var latlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
map = new google.maps.Map(document.getElementById('map'), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: latlng,
zoom: 12
});
var request = {
location: latlng,
radius: 500,
query: mySearch
};
infowindow = new google.maps.InfoWindow();
service = new google.maps.places.PlacesService(map);
service.textSearch(request, callback);
}
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
var place = results[i];
createMarker(results[i]);
}
}
}
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, place.website);
infowindow.open(map, this);
});
}
The code works fine however I am trying to retrieve more details about a place. I know about the place details at: https://developers.google.com/maps/documentation/javascript/places#place_details I'm just unsure where and how to adjust my code to say add in the places website. I'm struggling to work out where to get the reference and then how to use it. If someone could write it within my code that would be great.
Adjusted "createMarker" function (not tested):
function createMarker(place) {
var placeLoc = place.geometry.location;
if (place.icon) {
var image = new google.maps.MarkerImage(
place.icon, new google.maps.Size(71, 71),
new google.maps.Point(0, 0), new google.maps.Point(17, 34),
new google.maps.Size(25, 25));
} else var image = null;
var marker = new google.maps.Marker({
map: map,
icon: image,
position: place.geometry.location
});
var request = {
reference: place.reference
};
google.maps.event.addListener(marker,'click',function(){
service.getDetails(request, function(place, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
var contentStr = '<h5>'+place.name+'</h5><p>'+place.formatted_address;
if (!!place.formatted_phone_number) contentStr += '<br>'+place.formatted_phone_number;
if (!!place.website) contentStr += '<br><a target="_blank" href="'+place.website+'">'+place.website+'</a>';
contentStr += '<br>'+place.types+'</p>';
infowindow.setContent(contentStr);
infowindow.open(map,marker);
} else {
var contentStr = "<h5>No Result, status="+status+"</h5>";
infowindow.setContent(contentStr);
infowindow.open(map,marker);
}
});
});
}
working example

Google Maps API v3 multiple markers Infowindow

I've used the code below to display a map with multiple markers and infowindows. Now I have encountered the very common problem of the last infowindow showing up on all markers. I've tried all sorts of solutions including: http://you.arenot.me/2010/06/29/google-maps-api-v3-0-multiple-markers-multiple-infowindows/ and this one http://www.robertbolton.com/blog/google-maps-v3-multiple-markers-and-infowindows-in-a-loop but none of them fix the problem.
Here is my code:
var infowindow = null;
var geocoder;
var map;
$(document).ready(function() {
initialize();
});
function initialize() {
var myOptions = {
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP,
disableDefaultUI: true,
scrollwheel: false
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
setMarkers(map, people);
infowindow = new google.maps.InfoWindow({
content: "loading..."
});
}
var people = [
{"userid":"47","lastname":"lastname1","firstname":"firstname1","address":"Paris, France","phone1":"00000000000","phone2":"","email":"me#me.com"},
{"userid":"42","lastname":"lastname2","firstname":"firstname2","address":"Versaille, France","phone1":"0","phone2":"0","email":"me#me.com"}
];
function setMarkers(map, people) {
for (var i = 0; i < people.length; i++) {
var p = people[i];
geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': p["address"] }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
position: results[0].geometry.location,
map: map,
html: p["address"]
});
var contentString = "Some content";
google.maps.event.addListener(marker, "click", function () {
infowindow.setContent(this.html);
infowindow.open(map, this);
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
}
geocoding is an asynchronous request. So when you use geocoding inside the for-loop, the loop is already finished when you receive the results, i will always be 1 and point to the last item of people.
What you can do: split the marker-creation into 2 functions. 1 for the loop which calls the 2nd function that creates the markers:
remove the current function setMarkers and add the following 2 functions to your script:
function setMarkers(map,people) {
for (var i = 0; i < people.length; i++) {
setMarker(map, people[i])
}
}
function setMarker(map, people) {
var p=people;
geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': p["address"] }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
position: results[0].geometry.location,
map: map,
html: p["address"]
});
var contentString = "Some content";
google.maps.event.addListener(marker, "click", function () {
infowindow.setContent(this.html);
infowindow.open(map, this);
});
}
else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
The rest of your script may stay as it is.