0

我正在尝试根据表单提交中的 IP 地址地理位置获取显示位置信息的 Google 地图。

下面的 PHP 代码是这样工作的:如果我在文本框中输入一个 IP 地址,它将给我城市和国家。我需要自动获取相应城市的谷歌地图:

 <html>
<body>
<?php
if( !defined('LOADED') )
   die('You cannot access this file directly!');
function countryCityFromIP($ipAddr)
{
    $url = "http://api.ipinfodb.com/v3/ip-city/?key=5cfaab6c5af420b7b0f88d289571b990763e37b66761b2f053246f9db07ca913&ip=$ipAddr&format=json";
    $d = file_get_contents($url);
    return json_decode($d , true);
}

if(isset($_REQUEST['submit'])){
   $ip=countryCityFromIP($_REQUEST['ip']);

   //print_r($ip);
   $myString = "The City for the entered IP Address= ";
   $myString2 = "The Country for the entered IP Address= ";
   echo "<p style='text-align: center; font-size: 25px; font-family: georgia,palatino; color: #202020;'>".$myString.$ip['cityName']."</p>";
   echo "<p style='text-align: center; font-size: 25px; font-family: georgia,palatino; color: #202020;'>".$myString2.$ip['countryName']."</p>";
}
?>
<form method="post">
<center><input type="text" name="ip" style="font-size:25pt;height:30px;width:400px"/></center>
<center><input type="submit" name="submit" value="Search IP Location" style="font-size:15pt;height:40px;width:200px"/></center>
</form>
</body>
4

1 回答 1

3

您可以在其中获取所需位置的地图的代码。查找 GOOGLE 地理代码以获取更多信息

<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <title>Geocoding service</title>
    <link href="/maps/documentation/javascript/examples/default.css" rel="stylesheet">
    <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
    <script>
var geocoder;
var map;
function initialize() {
  geocoder = new google.maps.Geocoder();
  var latlng = new google.maps.LatLng(-34.397, 150.644);
  var mapOptions = {
    zoom: 8,
    center: latlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }
  map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
}

function codeAddress() {
  var address = document.getElementById('address').value;
  geocoder.geocode( { 'address': address}, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      map.setCenter(results[0].geometry.location);
      var marker = new google.maps.Marker({
          map: map,
          position: results[0].geometry.location
      });
    } else {
      alert('Geocode was not successful for the following reason: ' + status);
    }
  });
}

google.maps.event.addDomListener(window, 'load', initialize);

    </script>
  </head>
  <body>
    <div id="panel">
      <input id="address" type="textbox" value="Sydney, NSW">
      <input type="button" value="Geocode" onclick="codeAddress()">
    </div>
    <div id="map-canvas"></div>
  </body>
</html>

您可以根据需要修改此代码,

var address = document.getElementById('address').value;

在 var 地址中,您必须传递您的$myString.$ip['cityName'].变量。希望这可以帮助

于 2013-08-19T13:21:57.010 回答