当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - how to show user location on Google maps using "onclick" function?

问题描述:

I'm trying to build a website that shows a map and on top of it I want to display a button that takes you to your current location.

I'm using Google maps service to pull out the map, I also manage to get the user location by itself so all the JavaScript seems to be working fine but when add the function getlocation to the code and try to call it from the HTML it doesn't work. I believe that is probably not finding the function and I can't figure out why?

I will leave the code below:

<script>

var map;

function initialize() {

var miami = new google.maps.LatLng(41.85, -87.65);

var mapOptions = {

zoom: 4,

center: miami,

disableDefaultUI: true,

}

map = new google.maps.Map(document.getElementById('mymap'),

mapOptions);

var myloc = document.getElementById("try");

function getlocation () {

//code

// Try HTML5 geolocation

if(navigator.geolocation) {

navigator.geolocation.getCurrentPosition(function(position) {

var pos = new google.maps.LatLng(position.coords.latitude,

position.coords.longitude);

var infowindow = new google.maps.InfoWindow({

map: map,

position: pos,

content: 'Location found using HTML5.'

});

}, function() {

handleNoGeolocation(true);

});

} else {

// Browser doesn't support Geolocation

handleNoGeolocation(false);

}

}

function handleNoGeolocation(errorFlag) {

if (errorFlag) {

var content = 'Error: The Geolocation service failed.';

} else {

var content = 'Error: Your browser doesn\'t support geolocation.';

}

var options = {

map: map,

position: new google.maps.LatLng(60, 105),

content: content

};

var infowindow = new google.maps.InfoWindow(options);

}

}

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

</script>

I'm using inline style for everything. I'm somehow new into this of JavaScript so if could please tell me where is my error or what else do I need to make a button from the HTML call a function on JavaScript.

In addition here is the HTML button and map div

 <style>

html, body, #mymap{

height: 100%;

margin: 0px;

padding: 0px

}

</style>

<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true"></script>

<body>

<div id="try"><button onclick="getlocation()">Click here</button></div>

<div id="mymap"></div>

</body>

If you don't understand what my question is please also comment!

This is my first question here!

网友答案:
google.maps.event.addListener(map, 'click', function(event) {

    marker = new google.maps.Marker({position: event.latLng, map: map});

});
分享给朋友:
您可能感兴趣的文章:
随机阅读: