自动定位在textfield Google地图中

时间:2015-11-04 11:16:11

标签: javascript php html google-maps

当我写一些位置时,我试图自动获取文本字段内的位置!但它没有用,当我写东西时没有出现任何位置。

以下是代码:

 <!DOCTYPE html>
      <html>
      <head>
       <title>Google Maps JavaScript API v3 Example: Places Autocomplete</title>
      <script src="https://maps.googleapis.com/maps/api/js?sensor=false&libraries=places">
      type="text/javascript">
      function initialize() {
      var input = document.getElementById('searchTextField');
      var options = {componentRestrictions: {country: 'us'}};            
    new google.maps.places.Autocomplete(input, options); }         
       google.maps.event.addDomListener(window, 'load', initialize);
       </script>
     </head>
      <body>
      <label for="searchTextField">Please insert an address:</label>
      <input id="searchTextField" type="text" size="50">
      </body>
     </html>

2 个答案:

答案 0 :(得分:0)

试试这个:

JS

var input = document.getElementById('searchTextField');
var options = {componentRestrictions: {country: 'us'}};

new google.maps.places.Autocomplete(input, options);

HTML

<label for="searchTextField">Please Insert an address:</label>
<br>
<input id="searchTextField" type="text" size="50">

以下是适用的小提琴示例:http://jsfiddle.net/moinsam/SDPHm/light/ 我的建议是将JS与HTML分开。

答案 1 :(得分:0)

我尝试了您的代码,其中一个结束</script>代码存在问题:

<!DOCTYPE html>
<html>
   <head>
       <title>Google Maps JavaScript API v3 Example: Places Autocomplete</title>
       <script src="https://maps.googleapis.com/maps/api/js?sensor=false&libraries=places" type="text/javascript"></script><!-- You forgot closing this -->
       <!-- You forgot starting the below script tag -->
       <script>
       function initialize() {
         var input = document.getElementById('searchTextField');
         var options = {componentRestrictions: {country: 'us'}};            
         new google.maps.places.Autocomplete(input, options); 
       }         
       google.maps.event.addDomListener(window, 'load', initialize);
       </script>
  </head>

  <body>
      <label for="searchTextField">Please insert an address:</label>
      <input id="searchTextField" type="text" size="50">
  </body>
</html>

修改

如果您想获得用户的当前位置(国家/地区和城市),可以通过多种方式进行操作。您可以使用访问者IP地址获取该信息:

$ip = getenv('REMOTE_ADDR');
$addr = file_get_contents('http://api.hostip.info/get_json.php?ip='.$ip);
$addr = json_decode($addr, TRUE);
$countryAndCity = $addr["country_name"].", ".$addr["city"];
echo $countryAndCity;

请注意,这可能不准确,可能会被伪造。