简体   繁体   中英

API Google Maps Javascript Address to LatLng

I'm trying to use the Google Maps API on my website, and I want to convert an Address inputted by the user to LatLng and show the location on the map. I already know that I need to use the Geocoding function, but for some reason it's not working. Here's the code:

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
  html { height: 100% }
  body { height: 100%; margin: 0; padding: 0 }
  #map_canvas { height: 100% }
</style>
<script type="text/javascript"
  src="http://maps.googleapis.com/maps/api/js?key=AIzaSyBSkRxYKDW33Zng3Kmp_7IC_nom9JEEVwc&sensor=FALSE">
</script>
<script type="text/javascript">
  function initialize() {
    var mapOptions = {
      center: new google.maps.LatLng(-34.397, 150.644),
      zoom: 8,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
  }
  function moradaToLatLng(morada){

    var geocoder = new google.maps.Geocoder();
    if (geocoder) {
      alert("1");
        geocoder.geocode({
            'address': address
        }, function (results) {
            alert("2");
            map.setCenter(results[0].geometry.location);
            map.setZoom(16);
            var m = document.getElementById("morada").innerHTML = results[0].geometry.location;
            //criarPopup(address, results[0].geometry.location);
        });
    }
  }
</script>
</head>
<body onload="initialize()">
<div id="map_canvas" style="width:100%; height:80%"></div>
<div id="form">
  <input type="text" id="morada" value="Morada">
  <button id="btnMorada" onclick="moradaToLatLng(morada.value)">Ok</button>
</div>
</body>
</html>

For some reason, it doesn't enter the function and display alert("2"); EDIT.: I put all of my code

Add this line to your code:

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

as following:

 function moradaToLatLng(morada) {
            var address = document.getElementById('morada').value;
            var geocoder = new google.maps.Geocoder();
            if (geocoder) {
                alert("1");
                geocoder.geocode({
                    'address': address
                }, function (results) {
                    alert("2");
                    map.setCenter(results[0].geometry.location);
                    map.setZoom(16);
                    var m = document.getElementById("morada").innerHTML = results[0].geometry.location;
                    //criarPopup(address, results[0].geometry.location);
                });
            }
        }

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