简体   繁体   中英

How to find the current location(longitude and latitude) using Google Map?

I just want to ask how can I get the current latitude and longitude using Google Map? Because I am creating a Map Tool for adjusting maps in database. If there is a given latitude and longitude simply display the map. I have no problem with that. But if the longitude and latitude is NULL or 0. How can I get the exact latitude and longitude?

I have this PHP:

for ($i = 0; $i <= $companies_count; $i++) :
$company = $companies[$i];
$company_id = $company['company_id'];
$file_id = $addresses_file[$i]['company_id']; //file information from textfile
$file_latitude = $addresses_file[$i]['new_lat'];
$file_longitude = $addresses_file[$i]['new_long'];
foreach($addresses_file as $y){
  if($company_id == $y['company_id']){
    $lat = $y['new_lat'];
    $long = $y['new_long'];
  }else{
    $lat = $additionals[$company_id]['geo_lat'];
      $long = $additionals[$company_id]['geo_long'];
      if($lat == 0 || $lat == NULL){
              //set lat to current position
      }
      if($long == 0 || $long == NULL){
              //set long to current position
      }
    }
}
endfor;

...and my JavaScript:

var maps = {},
geocoder = null;
function showAddress(address, i) {
  if (geocoder) {
    geocoder.geocode( { 'address' : address },
      function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
          var id = i;
          var center = results[0].geometry.location;
          document.getElementById("lat_" + id).innerHTML = center.lat().toFixed(5);
          document.getElementById("long_" + id).innerHTML = center.lng().toFixed(5);
          maps[id].mapObj.setCenter(center);
          maps[id].marker.setPosition(center);
          $('html, body').animate({
            scrollTop: $("tr[rel='" + id + "']").offset().top
          }, 1000);
        }else{
          alert("Geocode was not successful for the following reason: " + status);
        }
      }
    );
  }
}

function fn_initialize() {
  geocoder = new google.maps.Geocoder();
  var hh_map = {
    init: function(lat, lon, z_lvl, label, id){
      var latlng = new google.maps.LatLng(lat, lon);
      var mapOptions = {
        zoom: z_lvl,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        streetViewControl: false,
        overviewMapControl: false,
        mapTypeControl: false,
        panControl: false,
        zoomControlOptions: {
          style: google.maps.ZoomControlStyle.SMALL,
          position: google.maps.ControlPosition.LEFT_BOTTOM
        },
        center: latlng,
      };                                        
      var map = new google.maps.Map(document.getElementById("map_canvas_" + id), mapOptions);
      var marker = new google.maps.Marker({
        map: map,
        position: map.getCenter(),
        title: label,
        draggable: true
      });
      google.maps.event.addListener(marker, 'dragend', function(e) { // update lat_{id}/long_{id}
        var center = marker.getPosition();
        document.getElementById("lat_" + id).innerHTML = center.lat().toFixed(5);
        document.getElementById("long_" + id).innerHTML = center.lng().toFixed(5);
      });
      maps[id] = {'mapObj' : map, 'marker' : marker};
    }
  };
$('.map_canvas').each(function(){
    if ($(this).data('lat') && $(this).data('long')) {
      hh_map.init($(this).data('lat'), $(this).data('long'), 16, $(this).data('label'), $(this).data('company_id'));
    }
  })
}

function loadScript() {
  var script = document.createElement("script");
  script.type = "text/javascript";
  script.src = "http://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&callback=fn_initialize";
  document.body.appendChild(script);
}

window.onload = loadScript;
$(document).ready(function(){
  //update address
  $('.save-button').each(function(index, elm){
    $(elm).click(function(){
      var id = $(this).attr("id"),
      val_lat = $('#lat_' + id).html(),
      val_long = $('#long_' + id).html();
      if (val_lat.length > 0 && val_long.length > 0) {
        var x = confirm("Are you sure you want to update this?");
        if(x == true){
          $('<form action="" method="POST">' +
          '<input type="hidden" name="company_id" value="' + id + '">' +
          '<input type="hidden" name="new_lat" value="' + val_lat + '">' +
          '<input type="hidden" name="new_long" value="' + val_long + '">' +
          '</form>').submit();
        }else{
          return false;
        }
      } else {
        alert('New locations are empty!');
      }
      return false;
    })
  })
  $('.revert-button').each(function(index, elm){ //revert address
    $(elm).click(function(){
      var id = $(this).attr("id"),
      val_lat = $('#lat_' + id).html(),
      val_long = $('#long_' + id).html();
      if (val_lat.length > 0 && val_long.length > 0) {
        var x = confirm("Are you sure you want to revert this?");
        if(x == true){
          $('<form action="" method="POST">' +
          '<input type="hidden" name="company_id" value="' + id + '">' +
          '<input type="hidden" name="new_lat" value="' + val_lat + '">' +
          '<input type="hidden" name="new_long" value="' + val_long + '">' +
          '</form>').submit();
        }else{
          return false;
        }
      } else {
        alert('New locations are empty!');
      }
      return false;
    })
  })
})

With JavaScript, you can use:

var center = map.getCenter();
alert(center.lat() + ', ' + center.lng());

The top answer shown in the linked duplicate question is for Google Maps V2.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM