2012-02-04 52 views
14

"My Location" in Google Maps javascript APIMostrar mi ubicación en Google Maps API v3

se le pidió Esta pregunta hace más de medio año. ¿Se ha actualizado Google Maps API v3 para usar el botón "Mi ubicación" que se encuentra en http://maps.google.com?

Mi ubicación es el control entre el hombre de Street View y los controles que parecen gamepad.

Si Google Maps API no proporciona Mi ubicación, ¿necesito escribir mi propia función de geolocalización HTML5 utilizando navigator.gelocation y luego crear mi propio control en Google Maps?

Respuesta

46

No, pero añadiendo su propio marcador basado en la ubicación actual es fácil:

var myloc = new google.maps.Marker({ 
    clickable: false, 
    icon: new google.maps.MarkerImage('//maps.gstatic.com/mapfiles/mobile/mobileimgs2.png', 
                new google.maps.Size(22,22), 
                new google.maps.Point(0,18), 
                new google.maps.Point(11,11)), 
    shadow: null, 
    zIndex: 999, 
    map: // your google.maps.Map object 
}); 

if (navigator.geolocation) navigator.geolocation.getCurrentPosition(function(pos) { 
    var me = new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude); 
    myloc.setPosition(me); 
}, function(error) { 
    // ... 
}); 
+1

Gracias. Terminé creando un control personalizado y agregando un oyente de clic. Cuando el oyente lo activó, hizo lo que usted escribió: agregue un marcador a la ubicación del usuario. – hobbes3

+0

Gracias amable señor – EmptyCup

+0

Muchas gracias !! Sin embargo, si usa esto, puede descargar la imagen alojada en [link] (maps.gstatic.com/mapfiles/mobile/mobileimgs2.png) y guardarla localmente en su servidor. Si esto no se hace, siempre estará dependiendo de la conexión de otro servidor más la suya. Al descargar la imagen, todo debería funcionar aún más uniforme – blastervla

2
//copy and paste this in your script section. 
if (navigator.geolocation) { 
    navigator.geolocation.getCurrentPosition(success, error); 
} else { 
    alert('location not supported'); 
} 

//callbacks 
function error(msg) { 
    alert('error in geolocation'); 
} 

function success(position) { 
    var lats = position.coords.latitude; 
    var lngs = position.coords.longitude; 
    alert(lats); 
    alert(lngs) 
}; 
4

Hemos hecho un componente de Google Maps API v3. Cualquiera puede usar en proyectos personalizados para agregar un control que muestra geolocalización actual con una sola línea de código:

var geoloccontrol = new klokantech.GeolocationControl(map, mapMaxZoom); 

después de incluir en la cabecera HTML este JavaScript:

<script src="https://cdn.klokantech.com/maptilerlayer/v1/index.js"></script> 

Ver:

http://www.maptiler.com/maptilerlayer/

para obtener un código de ejemplo y documentación.

Show My Location Control on Google Maps API v3

Se añade el control estándar para el mapa - y una vez tapping - que muestra el círculo azul alrededor de su ubicación con el tamaño del derivado de precisión de los datos de localización disponibles. Si no arrastra el mapa, lo mantendrá posicionado una vez que se mueva.

Este control se ha desarrollado para el visor generado automáticamente por el software http://www.maptiler.com/, que crea mosaicos para superposiciones de mapas y capas personalizadas a partir de imágenes y geodatos ráster.

+1

De alguna manera, el GeolocationControl no aparece para mí (incluso cuando uso exactamente el mismo código de los documentos). Toda la otra funcionalidad de la biblioteca funciona para mí. ¿Hay problemas conocidos con respecto a ese botón? – erikvdplas

+0

El icono de ubicación geográfica no se muestra después de incluir '\t var geoloccontrol = new klokantech.GeolocationControl (map, mapMaxZoom); 'en mi archivo –

3

tienes que hacerlo por tu cuenta. Aquí hay un fragmento de código para agregar el botón "Su ubicación". HTML

<div id="map">Map will be here</div> 

CSS

#map {width:100%;height: 400px;} 

JS

var map; 
var faisalabad = {lat:31.4181, lng:73.0776}; 

function addYourLocationButton(map, marker) 
{ 
    var controlDiv = document.createElement('div'); 

    var firstChild = document.createElement('button'); 
    firstChild.style.backgroundColor = '#fff'; 
    firstChild.style.border = 'none'; 
    firstChild.style.outline = 'none'; 
    firstChild.style.width = '28px'; 
    firstChild.style.height = '28px'; 
    firstChild.style.borderRadius = '2px'; 
    firstChild.style.boxShadow = '0 1px 4px rgba(0,0,0,0.3)'; 
    firstChild.style.cursor = 'pointer'; 
    firstChild.style.marginRight = '10px'; 
    firstChild.style.padding = '0px'; 
    firstChild.title = 'Your Location'; 
    controlDiv.appendChild(firstChild); 

    var secondChild = document.createElement('div'); 
    secondChild.style.margin = '5px'; 
    secondChild.style.width = '18px'; 
    secondChild.style.height = '18px'; 
    secondChild.style.backgroundImage = 'url(https://maps.gstatic.com/tactile/mylocation/mylocation-sprite-1x.png)'; 
    secondChild.style.backgroundSize = '180px 18px'; 
    secondChild.style.backgroundPosition = '0px 0px'; 
    secondChild.style.backgroundRepeat = 'no-repeat'; 
    secondChild.id = 'you_location_img'; 
    firstChild.appendChild(secondChild); 

    google.maps.event.addListener(map, 'dragend', function() { 
     $('#you_location_img').css('background-position', '0px 0px'); 
    }); 

    firstChild.addEventListener('click', function() { 
     var imgX = '0'; 
     var animationInterval = setInterval(function(){ 
      if(imgX == '-18') imgX = '0'; 
      else imgX = '-18'; 
      $('#you_location_img').css('background-position', imgX+'px 0px'); 
     }, 500); 
     if(navigator.geolocation) { 
      navigator.geolocation.getCurrentPosition(function(position) { 
       var latlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude); 
       marker.setPosition(latlng); 
       map.setCenter(latlng); 
       clearInterval(animationInterval); 
       $('#you_location_img').css('background-position', '-144px 0px'); 
      }); 
     } 
     else{ 
      clearInterval(animationInterval); 
      $('#you_location_img').css('background-position', '0px 0px'); 
     } 
    }); 

    controlDiv.index = 1; 
    map.controls[google.maps.ControlPosition.RIGHT_BOTTOM].push(controlDiv); 
} 

function initMap() { 
    map = new google.maps.Map(document.getElementById('map'), { 
     zoom: 15, 
     center: faisalabad 
    }); 
    var myMarker = new google.maps.Marker({ 
     map: map, 
     animation: google.maps.Animation.DROP, 
     position: faisalabad 
    }); 
    addYourLocationButton(map, myMarker); 
} 

$(document).ready(function(e) { 
    initMap(); 
}); 
Cuestiones relacionadas