How to set center of google map based on street ad

2019-07-10 11:40发布

问题:

I have just started working with the Google Maps API and Geocoding Service. I followed this tutorial and it was great.

Now I want to be able to create a map with a center based on a location ( "Vancvouer, BC" ) as opposed to latitude and longtitude as required when creating the map.

What I am trying to do is use a callback function named "initMap()" to initialize the map, and in that function I am creating a Geocoder object to get lang and long based on a location. ( "Vancvouer, BC" ).

Here's my initMap() function:

function initMap() {

    var geocoder1 = new google.maps.Geocoder();
    var center = getCenter(geocoder1, 'Vancouver, BC');

    if(center != null) {
        alert(center[0].geometry.location);
    }

    var map = new google.maps.Map(document.getElementById('map'), {
        zoom: 8,
        center: {lat: -34.397, lng: 150.644}
    });
}

This is how I am getting lang and long based on address:

function getCenter(geocoder, address) {
    geocoder.geocode({'address': address}, function(results, status) {
        if (status === google.maps.GeocoderStatus.OK) {
            console.log(results);
            var result = results[0].geometry.location.toJSON();
            return result;
        } else {
            alert('Geocode was not successful for the following reason: ' + status);
            // return null;
        }
    });
}

This will return a JSON object with the lat and lang I want, but when I try to access its values in initMap() using the if statement center is always undefined.

Once I am able to get the value for center I believe I would be able to set the center easy enough, but why I am not getting these values?

I think its a problem with scope and callback functions, but cant figure it out. Been stuck for a while, thought I'd reach out for help.

Thanks,

Matt

P.S. Let me know if you need any other info. First post on stackoverflow...

回答1:

The geocoder is asynchronous, you can't return anything from an asynchronous callback function. You need to use the returned data inside the callback function where/when it is available:

function setCenter(geocoder, address) {
  geocoder.geocode({
    'address': address
  }, function(results, status) {
    if (status === google.maps.GeocoderStatus.OK) {
      var map = new google.maps.Map(document.getElementById('map'), {
        zoom: 8,
        center: results[0].geometry.location
      });
    } else {
      alert('Geocode was not successful for the following reason: ' + status);
      // return null;
    }
  });
}

proof of concept fiddle

code snippet:

function initMap() {

  var geocoder1 = new google.maps.Geocoder();
  setCenter(geocoder1, 'Vancouver, BC');
}

function setCenter(geocoder, address) {
  geocoder.geocode({
    'address': address
  }, function(results, status) {
    if (status === google.maps.GeocoderStatus.OK) {
      var map = new google.maps.Map(document.getElementById('map'), {
        zoom: 8,
        center: results[0].geometry.location
      });
    } else {
      alert('Geocode was not successful for the following reason: ' + status);
      // return null;
    }
  });
}
google.maps.event.addDomListener(window, "load", initMap);
html,
body,
#map {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>

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



回答2:

You do not need to convert the results to Json. Use

    center[0].geometry.location

This can be assigned to the center property of the map object. To check for null:

    if (center[0] != null)


回答3:

Set center by address after map ini:

example:

set_center(address)

function set_center(address) {
    var geocoder = new google.maps.Geocoder();
    geocoder.geocode({address: address}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        map.setCenter(results[0].geometry.location);
      }
    })
  }

var "map" must be ini with google map, example

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