简体   繁体   中英

Maps API v3 geocoding

Straight to the point: I'm building a gmap with custom markers pulled via JSON. I also need to provide a search functionality; the nearest marker to the inputted postcode (AU).

Marker display (and other data from the array) works fine, it's this second part that has my ass kicked. I'm not great with JS. At the moment all I'm trying to do is return the Lat and Long of the inputted postcode, though if anyone can show me how to perform the whole function, that would be great. Can anyone point me in the right direction? JS and markup below, and thanks in advance for any assistance.

JavaScript:

function initialize() {
  /* Map setup */
  var latlng = new google.maps.LatLng(XXX, XXX);
  var mapOptions = {
     center: latlng,
     zoom: 16,
     mapTypeId: google.maps.MapTypeId.ROADMAP
  };
  /* Map initialise */
  var map = new google.maps.Map(document.getElementById("map-canvas"),
     mapOptions);

  /* set iconpath */
  var iconBase = '/path-to-icons';

  /* create a separate shadow icon */
  var markerShadow = {
     url: iconBase + 'icon_map-shadow.png',
     anchor: new google.maps.Point(15, 25)
  };

  /* Get JSON */
  jQuery.getJSON('/path-to/markers.json', function (mapdata) {
      $.each(mapdata, function (key, data) {
        var latlng = new google.maps.LatLng(data.lat, data.lng);
        var marker = new google.maps.Marker({
           position: latlng,
           map: map,
           icon: iconBase + 'icon_map.png',
           shadow: markerShadow,
           address: data.address,
           subaddress: data.subaddress,
           title: data.title
        });
        /* For the showing of the details */
        // TODO : MAKE THIS NEATER
        google.maps.event.addListener(marker, 'click', function () {
           $("#map-details .inner").hide();
           $("#map-details .inner span").html("");
           $("#map-details .inner .neareststore").html(marker.title);
           $("#map-details .inner .address").html(marker.address);
           $("#map-details .inner .sub-address").html(marker.subaddress);
           $("#map-details .inner").fadeIn(200);
        });
     });
  });
};
google.maps.event.addDomListener(window, 'load', initialize);

function geocode() {
  $("#search").submit(function(e){
    e.preventDefault();
    var currentloc = $("#postcode").val();
    var url = "http://maps.googleapis.com/maps/api/geocode/json?address="+currentloc+"+AU&sensor=false";
    $.getJSON(url, function(data) {
      //JSON function
    }); 
  };
};

Basic form HTML:

<form action="" method="post" id="search">
  <fieldset>
    <input name="postcode" id="postcode">
    <input type="submit" id="postcodesearch" value="search">
  </fieldset>
</form>




* EDIT * - Answered Can't answer my own question yet, but have solved this using the Haversine formula linked here: Google Maps Api v3 - find nearest markers

It needs some tidying but this is the gist, here for posterity. Thanks for the assistance all.

function rad(x) {return x*Math.PI/180;}
function find_closest_marker( _lat , _lng  ) {

    var lat = _lat;
    var lng = _lng;
    var R = 6371; // radius of earth in km
    var distances = [];
    var closest = -1;
    for( i=0;i<map.markers.length; i++ ) {
        var mlat = map.markers[i].position.lat();
        var mlng = map.markers[i].position.lng();
        var dLat  = rad(mlat - lat);
        var dLong = rad(mlng - lng);
        var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
            Math.cos(rad(lat)) * Math.cos(rad(lat)) * Math.sin(dLong/2) * Math.sin(dLong/2);
        var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
        var d = R * c;
        distances[i] = d;
        if ( closest == -1 || d < distances[closest] ) {
            closest = i;
        }
    }
    var closest = map.markers[closest];

    map.setCenter(closest.getPosition());
    $("#map-details .inner").hide();
    $("#map-details .inner span").html("");
    $("#map-details .inner .neareststore").html(closest.title);
    $("#map-details .inner .address").html(closest.address);
    $("#map-details .inner .sub-address").html(closest.subaddress);
    $("#map-details .inner").fadeIn(200);
}

$(document).ready(function(){
    $("#search").submit(function(e){
      e.preventDefault();
      var currentloc  = $("#postcode").val();
      var url         = "http://maps.googleapis.com/maps/api/geocode/json?address="+currentloc+"+AU&sensor=false";
      $.getJSON(url, function(data) {

        var lat = data.results[0].geometry.location.lat;
        var lng = data.results[0].geometry.location.lng;
        find_closest_marker(lat,lng)
      });
    });
});

Your second-to-last line has a syntax error; it should be }); instead of };

It should be this:

    function geocode() {
  $("#search").submit(function(e){
    e.preventDefault();
    var currentloc = $("#postcode").val();
    var url = "http://maps.googleapis.com/maps/api/geocode/jsonaddress="+currentloc+"+AU&sensor=false";
    $.getJSON(url, function(data) {
      //JSON function
    }); 
  });
};

I used http://www.dirtymarkup.com/ to check for syntax errors. It's really useful.

And, from https://developers.google.com/maps/documentation/geocoding/#JSON , it tells you the JSON output format. So, to get the Lat/Long, you would use:

data.results.geometry.location.lat and data.results.geometry.location.lng

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