google maps api cannot read placesservice

m_highlanderish picture m_highlanderish · Jan 26, 2016 · Viewed 9.3k times · Source

I am having a problem with Google's Maps API and its PlacesService. Even though I have the places library properly loaded it keeps saying "Cannot read property 'PlacesService' of undefined". The map itself works and loads. Any ideas? Here's the code:

<div id="map-canvas"></div>

<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3&libraries=place‌s"></script>
<script type="text/javascript">
    var myLatlng;
    var map;
    var marker;

    function initialize() {
        myLatlng = new google.maps.LatLng(fooLat, fooLng);

        var mapOptions = {
            zoom: 17,
            center: myLatlng,
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            scrollwheel: false,
            draggable: true
        };

        map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

        var service = new google.maps.places.PlacesService(map);

        var request = { placeId: 'fooPlaceId'};
        service.getDetails(request, callback);

        function callback (place, status) {
            if (status == google.maps.places.PlacesServiceStatus.OK) {
                marker = new google.maps.Marker({
                    position: place.position,
                    map: map,
                    title: place.name
                });
            }
        };
    }

    google.maps.event.addDomListener(window, 'load', initialize);
</script>

Update: I literally just tried a piece of code from Google itself and it gave me the same error.

Answer

151291 picture 151291 · Oct 27, 2016

This example requires the Places library. Include the libraries=places parameter when you first load the API with API Key.

For example:

<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places">