最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

javascript - Google Places API grab sublocality_level_1 if exists, else clear a text field - Stack Overflow

matteradmin9PV0评论

I've got a text field which allows users to enter their location which returns results (cities) from the Google Places API. Here's the code I'm using to fill in my form fields once a user has selected a location:

function fillInAddress() {
  // Get the place details from the autoplete object.
  var place = autoplete.getPlace();
  var lat = place.geometry.location.lat().toFixed(6);
  var lng = place.geometry.location.lng().toFixed(6);

  var ponents = place.address_ponents;
  for (var i = 0, ponent; ponent = ponents[i]; i++) {
        if (ponent.types[0] == 'locality') {
            $('#id_city').val(ponent['long_name'])
        }
        if (ponent.types[0] == 'administrative_area_level_1') {
            $('#id_state').val(ponent['short_name'])
        }
        if (ponent.types[0] == 'country') {
            $('#id_country_short').val(ponent['short_name'])
        }
        if (ponent.types[0] == 'country') {
            $('#id_country_long').val(ponent['long_name'])
        }
        if (ponent.types[0] == 'sublocality_level_1') {
            $('#id_region').val(ponent['long_name'])
        }else{
            $('#id_region').val('')
        }
    }
  $('#lat').val(lat)
  $('#lng').val(lng)
}

Pretty straight forward, but there's not always a "region" (or sublocality_level_1) selected with their location. What I'm attempting to do is clear the #id_region field of any old regions if the new location they've selected does not have a region/sublocality_level_1. The problem is that even if a sublocality_level_1 is present, the code still seems to hit the "else" statement which clears the #id_region text field.

Any idea what I'm doing wrong here?

I've got a text field which allows users to enter their location which returns results (cities) from the Google Places API. Here's the code I'm using to fill in my form fields once a user has selected a location:

function fillInAddress() {
  // Get the place details from the autoplete object.
  var place = autoplete.getPlace();
  var lat = place.geometry.location.lat().toFixed(6);
  var lng = place.geometry.location.lng().toFixed(6);

  var ponents = place.address_ponents;
  for (var i = 0, ponent; ponent = ponents[i]; i++) {
        if (ponent.types[0] == 'locality') {
            $('#id_city').val(ponent['long_name'])
        }
        if (ponent.types[0] == 'administrative_area_level_1') {
            $('#id_state').val(ponent['short_name'])
        }
        if (ponent.types[0] == 'country') {
            $('#id_country_short').val(ponent['short_name'])
        }
        if (ponent.types[0] == 'country') {
            $('#id_country_long').val(ponent['long_name'])
        }
        if (ponent.types[0] == 'sublocality_level_1') {
            $('#id_region').val(ponent['long_name'])
        }else{
            $('#id_region').val('')
        }
    }
  $('#lat').val(lat)
  $('#lng').val(lng)
}

Pretty straight forward, but there's not always a "region" (or sublocality_level_1) selected with their location. What I'm attempting to do is clear the #id_region field of any old regions if the new location they've selected does not have a region/sublocality_level_1. The problem is that even if a sublocality_level_1 is present, the code still seems to hit the "else" statement which clears the #id_region text field.

Any idea what I'm doing wrong here?

Share Improve this question asked Apr 21, 2017 at 19:45 lexbuckeyelexbuckeye 732 silver badges9 bronze badges 1
  • 1 You are only looking at the first member of the types array, there are usually more than that. – geocodezip Commented Apr 21, 2017 at 20:26
Add a ment  | 

2 Answers 2

Reset to default 4

The problem exists because of the structure of your if...else for a region. Because you are in a loop if there is any ponent in the ponents array after the one that is a region it will ... clear the region.

Remove the else from the loop. Clear the region before you start looping. That way if there is a region in the set, you'll fill it in and if there isn't it will stay empty.

function fillInAddress() {
  // Get the place details from the autoplete object.
  var place = autoplete.getPlace();
  var lat = place.geometry.location.lat().toFixed(6);
  var lng = place.geometry.location.lng().toFixed(6);

  var ponents = place.address_ponents;

  $('#id_region').val('');

  for (var i = 0, ponent; ponent = ponents[i]; i++) {
        if (ponent.types[0] == 'locality') {
            $('#id_city').val(ponent['long_name'])
        }
        if (ponent.types[0] == 'administrative_area_level_1') {
            $('#id_state').val(ponent['short_name'])
        }
        if (ponent.types[0] == 'country') {
            $('#id_country_short').val(ponent['short_name'])
        }
        if (ponent.types[0] == 'country') {
            $('#id_country_long').val(ponent['long_name'])
        }
        if (ponent.types[0] == 'sublocality_level_1') {
            $('#id_region').val(ponent['long_name'])
        }
    }
  $('#lat').val(lat)
  $('#lng').val(lng)
}

In addition to what @gforce301 said, you also need to process through all the types in the ponent:

  var ponents = place.address_ponents;
  $('#id_region').val('')
  for (var i = 0, ponent; ponent = ponents[i]; i++) {
    for (var j = 0; j < ponent.types.length; j++) {
      if (ponent.types[j] == 'locality') {
        $('#id_city').val(ponent['long_name'])
      }
      if (ponent.types[j] == 'administrative_area_level_1') {
        $('#id_state').val(ponent['short_name'])
      }
      if (ponent.types[j] == 'country') {
        $('#id_country_short').val(ponent['short_name'])
      }
      if (ponent.types[j] == 'country') {
        $('#id_country_long').val(ponent['long_name'])
      }
      if (ponent.types[j] == 'sublocality_level_1') {
        $('#id_region').val(ponent['long_name'])
      }
    }

proof of concept fiddle (places with sublocality_level_1: Brooklyn, NY; Śródmieście, Warsaw, Poland)

code snippet:

function initAutoplete() {
  // Create the autoplete object, restricting the search to geographical
  // location types.
  autoplete = new google.maps.places.Autoplete(
    /** @type {!HTMLInputElement} */
    (document.getElementById('autoplete')), {
      types: ['geocode']
    });

  // When the user selects an address from the dropdown, populate the address
  // fields in the form.
  autoplete.addListener('place_changed', fillInAddress);
}
google.maps.event.addDomListener(window, "load", initAutoplete);

function fillInAddress() {
  // Get the place details from the autoplete object.
  var place = autoplete.getPlace();
  var lat = place.geometry.location.lat().toFixed(6);
  var lng = place.geometry.location.lng().toFixed(6);

  var ponents = place.address_ponents;
  $('#id_region').val('')
  for (var i = 0, ponent; ponent = ponents[i]; i++) {
    for (var j = 0; j < ponent.types.length; j++) {
      if (ponent.types[j] == 'locality') {
        $('#id_city').val(ponent['long_name'])
      }
      if (ponent.types[j] == 'administrative_area_level_1') {
        $('#id_state').val(ponent['short_name'])
      }
      if (ponent.types[j] == 'country') {
        $('#id_country_short').val(ponent['short_name'])
      }
      if (ponent.types[j] == 'country') {
        $('#id_country_long').val(ponent['long_name'])
      }
      if (ponent.types[j] == 'sublocality_level_1') {
        $('#id_region').val(ponent['long_name'])
      } else {
        // $('#id_region').val('')
      }
    }
  }
  $('#lat').val(lat)
  $('#lng').val(lng)
}
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maps.googleapis./maps/api/js?libraries=places"></script>
<div id="locationField">
  <input id="autoplete" placeholder="Enter your address" type="text" />
</div>

<table id="address">
  <tr>
    <td class="label">Street address</td>
    <td class="slimField">
      <input class="field" id="street_number" disabled="true" />
    </td>
    <td class="wideField" colspan="2">
      <input class="field" id="route" disabled="true" />
    </td>
  </tr>
  <tr>
    <td class="label">City</td>
    <!-- Note: Selection of address ponents in this example is typical.
             You may need to adjust it for the locations relevant to your app. See
             https://developers.google./maps/documentation/javascript/examples/places-autoplete-addressform
        -->
    <td class="wideField" colspan="3">
      <input class="field" id="id_city" disabled="true" />
    </td>
  </tr>
  <tr>
    <td class="label">State</td>
    <td class="slimField">
      <input class="field" id="id_state" disabled="true" />
    </td>
    <td class="label">Region</td>
    <td class="wideField">
      <input class="field" id="id_region" disabled="true" />
    </td>
  </tr>
  <tr>
    <td class="label">Country</td>
    <td class="wideField" colspan="3">
      <input class="field" id="id_country_long" disabled="true" />
    </td>
  </tr>
  <tr>
    <td class="label">Country</td>
    <td class="wideField" colspan="3">
      <input class="field" id="id_country_short" disabled="true" />
    </td>
  </tr>
</table>
<input id="lat" />
<input id="lng" />

Articles related to this article

Post a comment

comment list (0)

  1. No comments so far