Skip to content Skip to sidebar Skip to footer

Google Maps V3 - How To Center Using An Address On Initialize?

Using Google Maps API v3, is there a way to set the center of the map on initialize? I have a workaround using this code: var geocoder; var map; function initialize() { geo

Solution 1:

Well a simple solution could be to initialize the map in your codeAddress function:

var geocoder, map;

functioncodeAddress(address) {
    geocoder = new google.maps.Geocoder();
    geocoder.geocode({
        'address': address
    }, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            var myOptions = {
                zoom: 8,
                center: results[0].geometry.location,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            }
            map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

            var marker = new google.maps.Marker({
                map: map,
                position: results[0].geometry.location
            });
        }
    });
}

This should solve the problem.

Solution 2:

This is an amazing answer that really helped me get super far. The only issue now is that setCenter is no longer valid in the JavaScript API. Here's my example using fitBounds, ES6 arrow functions to access a this reference to the google map angular component, and finally implementing ngOnChanges to listen for changes to an address text field and re-render the map accordingly.

ngOnChanges(changes: SimpleChanges) {
        const newFormattedAddress = changes['formattedAddress']?.currentValue;
        if (!newFormattedAddress) {
            return;
        }

        // if we received an update to the formattedAddress from the search boxconst geocoder = new google.maps.Geocoder();
        geocoder.geocode(
            {
                address: newFormattedAddress
            },
            (results: GeocoderResult[], status: GeocoderStatus) => {
                if (status === GeocoderStatus.OK && results.length > 0) {
                    const firstResult = results[0].geometry;
                    const bounds = new google.maps.LatLngBounds();

                    if (firstResult.viewport) {
                        // Only geocodes have viewport.
                        bounds.union(firstResult.viewport);
                    } else {
                        bounds.extend(firstResult.location);
                    }

                    this.map.fitBounds(bounds);
                }
            }
        );
    }

External references and credit for the fitBounds code: https://kevinkreuzer.medium.com/how-to-implement-an-address-search-with-angular-and-google-maps-32a2df09f8e9

kevinkreuzer.medium.com - Google Address Autocomplete feature using Angular

Post a Comment for "Google Maps V3 - How To Center Using An Address On Initialize?"