简体   繁体   中英

Using google maps api, how to prompt coordinates from the user and create path

I need to be able to collect data from user and then store it into variables so I can use them to create an itinerary path one a map using the polyline class from google maps api. I tried it a few ways and the closest i got is as such:

<!DOCTYPE html>
<html>
<head>
<script src="http://maps.googleapis.com/maps/api/js"></script>
<script>
function initialize(){

var latitude;
var longitude;
var latDest;
var longitudeDest;
var mapProp = {

    center: new google.maps.LatLng(52.395715,4.888916),
    zoom: 5,
    mapTypeId: google.maps.MapTypeId.ROADMAP 
};

var map = new google.maps.Map(document.getElementById("googleMap"), mapProp);
document.getElementById('submit').addEventListener('click', function() {
      latitude = document.getElementById('latitude').value;
      longitude = document.getElementById('longitude').value;
      latDest = document.getElementById('latDest').value;
      longitudeDest = document.getElementById('longitudeDest').value;
    });

var start = new google.maps.LatLng(latitude,logitude);
var dest = new google.maps.LatLng(latDest,longitudeDest);

var myTrip=[start,dest]
var flightPath=new google.maps.Polyline({
    path:myTrip,
    strokeColor:"#0000FF",
    strokeOpacity:0.8,
    strokeWeight:2
});

flightPath.setMap(map);
}

}

google.maps.event.addDomListener(window, 'load', initialize)


</script>
</head>

<body>
<div id="googleMap" style="width:500px;height:380px;"></div>
<form>
     <label>Start Lattitude</label><input type = "text" name = "latitude"/>    <br>
     <label>Start Longitude</label><input type = "text" name = "longitude"/><br>
     <label>Destination Latitude</label><input type = "text" name = "latDest"/><br>
     <label>Destination Longitude</label><input type = "text" name = "longitudeDest"/><br>
     <input type = "submit" name = "submit">

</form>
</body>

</html>

The result of this code is one that does not actually draw the path i need. The page is reloaded but the path does not appear, and everything is the same.

I managed to fix it. The problem was that I declared the 'map' variable inside the initialize function, but then I called it outside. I had to declare the var 'map' outside the function so that I could use the variable elsewhere. The problem here was just the scope of one variable.

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