How to geocode an address into lat/long with Google maps

前端 未结 1 376
北海茫月
北海茫月 2021-01-03 12:25

I want to be able to plot several companies on a google map and understand I need to geocode these.

I also have the code below that plot\'s multiple markers on a map

相关标签:
1条回答
  • 2021-01-03 12:50

    you could use google's geocoding to obtain coordinates of your post codes

    EDIT: I don't really like you changing the sense of the question like that but ok. Please try sth like that (its not tested):

    // Creating an array that will contain the coordinates 
    // for New York, San Francisco, and Seattle
    var places = [];
    
    // Adding a LatLng object for each city
    //places.push(new google.maps.LatLng(40.756, -73.986));
    //places.push(new google.maps.LatLng(37.775, -122.419));
    //places.push(new google.maps.LatLng(47.620, -122.347));
    //places.push(new google.maps.LatLng(-22.933, -43.184));
    var result;
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.open("GET", "http://maps.googleapis.com/maps/api/geocode/json?address=your+code&sensor=false",true);
     xmlhttp.onreadystatechange=function() {
      if (xmlhttp.readyState==4) {
           result = eval('(' + xmlhttp.responseText + ')');
    if (result.status == "OK") {
    var location = new google.maps.LatLng(result.results[0].geometry.location.lat, result.results[0].geometry.location.lng);
    places.push(location);
    

    this should probably work, despite possible minor errors.

    EDIT2: I have just now found simpler solution:

    // Creating an array that will contain the coordinates 
    // for New York, San Francisco, and Seattle
    var places = [];
    
    // Adding a LatLng object for each city
    //places.push(new google.maps.LatLng(40.756, -73.986));
    //places.push(new google.maps.LatLng(37.775, -122.419));
    //places.push(new google.maps.LatLng(47.620, -122.347));
    //places.push(new google.maps.LatLng(-22.933, -43.184));
    var geocoder = new google.maps.Geocoder();
    geocoder.geocode( { 'address': "your+code"}, 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
        //});
        places.push(results[0].geometry.location);
      } else {
        alert("Geocode was not successful for the following reason: " + status);
      }
    });
    
    0 讨论(0)
提交回复
热议问题