Home > OS >  Google Maps API Finding Details
Google Maps API Finding Details

Time:11-02

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=AIzaSyB4mivUi9qIAPD1PUxQwFfwA0ttCbNcATw&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.

CodePudding user response:

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