Chris S
Chris S

Reputation: 225

Bring in Google maps 'infowindow' information for current location

I am using the Google Maps Javascript API. The sample code; I think gets me close but doesn't accomplish what I hoped for.

I hard code a 'placeid' I am hoping to bring in my current location instead. I do bring in my current location in the sample code but the Infowindow information is hard coded.

I am hoping to learn how to bring in both the 'Current Location' marker and 'Infowindow' place information dynamically without the need to hard code it.

My broken script follows>>

<script>
    function initMap() {
        var map = new google.maps.Map(document.getElementById('map'), {
            center: {
                lat: 42.0491125,
                lng: -92.91123340000001
            },
            zoom: 12
        });

        var infowindow = new google.maps.InfoWindow();
        //       var infoWindow = new google.maps.InfoWindow({map: map});
        var service = new google.maps.places.PlacesService(map);
        service.getDetails({
            // I would like to bring in the current position not a static place id
            placeId: 'EioxMDEgRSBNYWluIFN0LCBNYXJzaGFsbHRvd24sIElBIDUwMTU4LCBVU0E'
        }, function(place, status) {
            if (status === google.maps.places.PlacesServiceStatus.OK) {
                var marker = new google.maps.Marker({
                    map: map,
                    position: place.geometry.location
                });
                google.maps.event.addListener(marker, 'click', function() {
                    infowindow.setContent('<div><strong>' + place.name + '</strong><br>' +
                        'lat lng: ' + place.geometry.location + '<br>' +
                        place.formatted_address + '</div>');
                    infowindow.open(map, this);
                });
            }
        });

        var infoWindow = new google.maps.InfoWindow({
            map: map
        });

        // Try HTML5 geolocation.
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(function(position) {
                var pos = {
                    lat: position.coords.latitude,
                    lng: position.coords.longitude
                };

                infoWindow.setPosition(pos);
                infoWindow.setContent('Home Point.');
                map.setCenter(pos);

                var marker = new google.maps.Marker({

                    title: 'Your current location',
                    map: map,
                    //  title: 'Your current location'
                });

            }, 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>
</head>

<body>
    <div id="map"></div>
    <script async defer src="https://maps.googleapis.com/maps/api/js? key=YOUR_API_KEY&libraries=places&callback=initMap">
    </script>
</body>

</html>

Upvotes: 0

Views: 1732

Answers (1)

Vadim Gremyachev
Vadim Gremyachev

Reputation: 59338

You could combine Geolocation service to determine the current location and then Reverse Geocoding to resolve address information (inc. place id) as demonstrated below

function initMap() {
	var map = new google.maps.Map(document.getElementById('map'), {
		center: { lat: 42.0491125, lng: -92.91123340000001 },
		zoom: 12
	});



	var infoWindow = new google.maps.InfoWindow({ map: map });


	// Try HTML5 geolocation.
	if (navigator.geolocation) {
		navigator.geolocation.getCurrentPosition(function (position) {
			var pos = {
				lat: position.coords.latitude,
				lng: position.coords.longitude
			};


			resolvePlace(pos,
				function (place) {

					var marker = new google.maps.Marker({
						title: place.formatted_address,
						map: map,
						position: pos
					});


					//infoWindow.setPosition(pos);
					infoWindow.setContent(place.formatted_address);
					map.setCenter(pos);
					infoWindow.open(map,marker);

				},
				function (status) {
					infoWindow.setPosition(pos);
					infoWindow.setContent('Geocoder failed due to: ' + status);
				});


		}, function () {
			handleLocationError(true, infoWindow, map.getCenter());
		});
	} else {
		// Browser doesn't support Geolocation
		handleLocationError(false, infoWindow, map.getCenter());
	}
}


function resolvePlace(pos, success, error) {

	var geocoder = new google.maps.Geocoder;
	geocoder.geocode({ 'location': pos }, function (results, status) {
		if (status === google.maps.GeocoderStatus.OK) {
			if (results[0]) {
				success(results[0]);
			} else {
				error('No results found');
			}
		} else {
			error(status);
		}
	});

}




function handleLocationError(browserHasGeolocation, infoWindow, pos) {
	infoWindow.setPosition(pos);
	infoWindow.setContent(browserHasGeolocation ?
		'Error: The Geolocation service failed.' :
		'Error: Your browser doesn\'t support geolocation.');
}
html, body {
        height: 100%;
        margin: 0;
        padding: 0;
}
#map {
        height: 100%;
}
<div id="map"></div>
<script async defer
src="https://maps.googleapis.com/maps/api/js?libraries=places&callback=initMap">
</script>

Plunker

Upvotes: 2

Related Questions