谷歌地图Lat/Long finder脚本

Google Maps Lat/Long finder script

本文关键字:finder 脚本 Long Lat 谷歌地图      更新时间:2023-09-26

我正在到处寻找一个脚本,我可以在输入框中添加地址或邮政编码,并在另一个输入框中显示谷歌纬度和经度。

我发现这个网站是这样做的:

http://www.doogal.co.uk/LatLong.php

但我不需要那么多,只需要寻找有搜索、纬度和经度部分的部分。

有人能提供任何信息、url或脚本来做到这一点吗?

我能找到的只有地图地址。。。。我只需要地址到纬度和经度。

如果使用Google Maps API,对地址进行地理编码非常简单。address是用户输入街道地址的文本字段。latlng是一个文本字段,用于保存输出的纬度/经度。

$('#searchButton').click(function() {
  var geocoder = new google.maps.Geocoder();
  geocoder.geocode( {'address': $('#address').val() }, function(data, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      $('#latlng').val(data[0].geometry.location.lat+", "+data[0].geometry.location.lng);
    else {
      alert("Geocode was not successful for the following reason: " + status);
    }
  });
  return false;
});

请参阅https://google-developers.appspot.com/maps/documentation/javascript/examples/geocoding-simple

他们在该页面上使用的代码是:

function Geocode()
            {
                $("#locations").html("");
                $("#error").html("");
                // geocode with google.maps.Geocoder
                var localSearch = new google.maps.Geocoder();
                var postcode = $("#postcode").val();
                localSearch.geocode({ 'address': postcode },
                    function(results, status) {
                        if (results.length == 1) {
                            var result = results[0];
                            var location = result.geometry.location;
                            GotoLocation(location);
                        }
                        else if (results.length > 1) {
                            $("#error").html("Multiple addresses found");
                            // build a list of possible addresses
                            var html = "";
                            for (var i=0; i<results.length; i++) {
                                html += '<a href="javascript:GotoLocation(new google.maps.LatLng(' + 
                                    results[i].geometry.location.lat() + ', ' + results[i].geometry.location.lng() + '))">' + 
                                    results[i].formatted_address + "</a><br/>";
                            }
                            $("#locations").html(html);
                        }
                        else {
                            $("#error").html("Address not found");
                        }
                    });
            }

#postcode是您在该站点一侧键入地址的位置,而for循环中的results[i].geometry.location.lat() + ', ' + results[i].geometry.location.lng()将是您的纬度/经度。。。

您需要获得一个API密钥并实现Google Geocoding API。

另外,geocoder.us还提供免费解决方案。

我构建了一个Latitude&我的网站的经度查找器:

请参阅:https://www.revilodesign.de/tools/google-maps-latitude-longitude-finder/

function initAutocomplete() {
	
	var markers = [];
	
	autocomplete = new google.maps.places.Autocomplete((document.getElementById('address')),{
		types: ['geocode']
	});
	
	var myLatLng = {
		lat			:	52.520008,
		lng			:	13.404954
	};
		
	var map		=	new google.maps.Map(document.getElementById('map'), {
		zoom		:	2,
		center		:	myLatLng
	});
	
	
	// START BY CLICK
	jQuery('div#find').on('click', function() {
		LatLngSearch();			
	});
	
	// START BY PRESS ENTER
	jQuery('#address').bind("enterKey",function(e){
		LatLngSearch();	
	});
	jQuery('#address').keyup(function(e){
		if(e.keyCode == 13) {
			LatLngSearch();
		}
	});
	
	// DELETE ALL MARKERS
	function DeleteMarkers() {
		for (var i = 0; i < markers.length; i++) {
			markers[i].setMap(null);
		}
		markers = [];
	};
	
	// SHOW LAT LNG		
	function LatLngSearch(  ) {
		
		var value	=	jQuery('input#address').val();
		
		if ( value ) {
			var request		=	$.ajax({
				url			:	"ajax.php",
				method		:	"POST",
				data		:	{ 
									address		:	value
								},
				dataType	:	'json',
				success		:	function(result) {
	  
					console.log(result);
					
					if ( result['lat'] && result['lng'] ) {
	    
						DeleteMarkers();
	    
						jQuery('div#geometry').append('<p><strong>Latitude:</strong> <input readonly="" value="' + result['lat'] + '" /></p>');
	      
						jQuery('div#geometry').append('<p><strong>Longitude:</strong> <input readonly="" value="' + result['lng'] + '" /></p>');
						
						var searchLatLng = {
							lat			:	result['lat'],
							lng			:	result['lng']
						};
						
						// CENTER MAP
						var map		=	new google.maps.Map(document.getElementById('map'), {
							zoom		:	14,
							center		:	searchLatLng
						});
						
						var marker = new google.maps.Marker({
							map			:	map,
							position	:	searchLatLng,
							animation	:	google.maps.Animation.DROP
			            });
			            
			            var infowindow	=	new google.maps.InfoWindow({
							content: '<strong>Lat:</strong> ' + result['lat'] + '<br><strong>Lng:</strong> ' + result['lng']
						});
						infowindow.open(map,marker);
						
						// ADD MARKER TO ARRAY
						markers.push(marker);
					}
					
				},
				error		:	function (xhr, ajaxOptions, thrownError) {
					alert(xhr.status);
					alert(thrownError);
				}
			});
		}
	}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places&callback=initAutocomplete" async defer></script>
<div id="finder">
	<div id="finder-search">
		<input id="address" type="text" />
		<div id="find" class="btn button scale-minus">Search</div>
	</div>
	<div id="geometry"></div>
	<div id="map"></div>
</div>

和ajax.php

$address            =   $_POST['address'];
$address            =   str_replace(array('ä','ü','ö','ß'), array('ae', 'ue', 'oe', 'ss'), $address );
$address            =   preg_replace("/[^a-zA-Z0-9'_'s]/", "", $address);
$address            =   strtolower($address);
$address            =   str_replace( array(' ', '--'), array('-', '-'), $address );                     
$address            =   'https://maps.googleapis.com/maps/api/geocode/json?address=' . $address . '&key=YOUR_API_KEY';
$json               =   file_get_contents($address);
$obj                =   json_decode($json); 
$datas['lat']       =   $obj->results[0]->geometry->location->lat;
$datas['lng']       =   $obj->results[0]->geometry->location->lng;
echo json_encode( $datas );
<form>
                <div class="form-group">
                  <label for="address">Lat Long of Location :</label>
                  <input type="text" class="form-control" id="address" placeholder="Enter Address to Find Lat Long">
                  <input id="submit" type="button" class="btn btn-primary" value="Get Lat Long" />
                          <input id="lat" type="hidden"/>
                      <input id="lng" type="hidden"/>
                </div>
                </form>


          </div>
          <div class="card-footer">
           <label for="lati">Latitude : </label><input id="lati" type="text" disabled />
            <label for="longi">Longitude : </label><input id="longi" type="text" disabled />
          </div>
          <div id="latlong"></div>
          <div id="temp"></div>
<div id="map"></div>
        </div>
      </div>
simply add
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=YOUR API KEY&#38;callback=initMap" async defer/>

<script>
      function initMap() {
         var map = new google.maps.Map(document.getElementById('map'), {
           zoom: 8,
           center: {lat: -34.397, lng: 150.644}
         });
         var geocoder = new google.maps.Geocoder();
         document.getElementById('submit').addEventListener('click', function() {
           geocodeAddress(geocoder, map);
         });
       }
       function geocodeAddress(geocoder, resultsMap) {
         var address = document.getElementById('address').value;
         if( address===''){
 alert("Please Enter Address to find Latitude Longitude...!!!!!!");
 return false;
 }
         geocoder.geocode({'address': address}, function(results, status) {
           if (status === 'OK') {
             resultsMap.setCenter(results[0].geometry.location);
              var info="<h4> Latitude and Longitude : "+results[0].geometry.location+"</h4>";
              var latlo="<h3>Lat Long of  "+address+"   "+results[0].geometry.location+"</h3>";
             var latlong1 = latlo;
              document.getElementById('latlong').innerHTML=latlong1;
              document.getElementById('lat').value=results[0].geometry.location.lat();
              document.getElementById('lng').value=results[0].geometry.location.lng();
               document.getElementById('lati').value=results[0].geometry.location.lat();

              var infowindow = new google.maps.InfoWindow({
           content: info
         });
             var marker = new google.maps.Marker({
               map: resultsMap,
               position: results[0].geometry.location,
               title: 'LatLongfinder Result'
             });
              infowindow.setContent(results[0].geometry.location.lat());
         infowindow.open(resultsMap, marker);
           } else {
             alert('Geocode was not successful for the following reason: ' + status);
           }
         });
       }
     </script>

我在我的网站latlongfinder 中使用了它