简体   繁体   中英

Google maps API Marker not marking my location

I'm new here and I'm having problems with an university work. The thing is I have to display a marker on user's current position, but it isn't working at all and I can't imagine why

 <html>
<head>
<title>Blank Cordova Mobile App Project Template (Lite)</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" http-   equiv="Content-type" content="text/html; charset=utf-8">

<!-- see http://webdesign.tutsplus.com/tutorials/htmlcss-tutorials/quick-tip-dont-forget-the-viewport-meta-tag -->
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
<style>
    /* following two viewport lines are equivalent to the meta viewport statement above, needed for Windows */
    @-ms-viewport { width: 100vw ; zoom: 100% ; }  @viewport { width: 100vw ; zoom: 100% ; }
    @-ms-viewport { user-zoom: fixed ; }           @viewport { user-zoom: fixed ; }
</style>

<style type="text/css">
div#map {
position: relative;
 }
 div#crosshair {
position: absolute;
top: 192px;
height: 19px;
width: 19px;
left: 50%;
margin-left: -8px;
display: block;
background: url(crosshair.gif);
background-position: center center;
background-repeat: no-repeat;
}
</style>

<script src="cordova.js"></script>          <!-- phantom library, needed for Cordova api calls, added during build -->
<script src="js/app.js"></script>
           <!-- recommended location of your JavaScript code relative to other JS files -->
<script src="xdk/init-dev.js"></script>     <!-- normalizes device and document ready events, see README for details -->

<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
/*The map starts tracing the device's location from the very start, the problem is that the first marker isn't working*/

 var map;
 var geocoder;
 var centerChangedLast;
 var reverseGeocodedLast;
 var currentReverseGeocodeResponse;

 var directions = null;

 var distance = null; // km

 var pos;
 var kmh = position.coords.speed;

 //This function traces the device position
 function initialize() {
 map = new google.maps.Map(document.getElementById("map_canvas"), {
 center: {lat: -34.397, lng: 150.644},
 zoom: 11
 });
 geocoder = new google.maps.Geocoder();
 setupEvents();
 //centerChanged(); I've commented this because isn't affecting the system
 var infoWindow = new google.maps.InfoWindow({"map_canvas": map});

 // Try HTML5 geolocation.
 if (navigator.geolocation) {
  navigator.geolocation.getCurrentPosition(function(position) {
   pos = {
    lat: position.coords.latitude,
    lng: position.coords.longitude
  };

  infoWindow.setPosition(pos);
  infoWindow.setContent('Location found.');
  map.setCenter(pos);
   }, function() {
  handleLocationError(true, infoWindow, map.getCenter());
   });
  } else {
  // Browser doesn't support Geolocation
  handleLocationError(false, infoWindow, map.getCenter());
  }

  var markme = new google.maps.Marker({
                            title : "Title",
                            position : pos,
                            map: map,
                     });
   markme.setMap(map);
   }
  //Error Treatment
function handleLocationError(browserHasGeolocation, infoWindow, pos) {
infoWindow.setPosition(pos);
infoWindow.setContent(browserHasGeolocation ?
                    'Error: The Geolocation service failed.' :
                    'Error: Your browser doesn\'t support geolocation.');
}


//Sets events
 function setupEvents() {
 reverseGeocodedLast = new Date();
 centerChangedLast = new Date();
 setInterval(function() {
  if((new Date()).getSeconds() - centerChangedLast.getSeconds() > 1) {
    if(reverseGeocodedLast.getTime() < centerChangedLast.getTime())
      reverseGeocode();
  }
}, 1000);
google.maps.event.addListener(map, 'zoom_changed', function() {
  document.getElementById("zoom_level").innerHTML = map.getZoom();
 });
 google.maps.event.addListener(map, 'center_changed', centerChanged);
                 google.maps.event.addDomListener(document.getElementById('crosshair'),'dblclick'    , function() {
   map.setZoom(map.getZoom() + 1);
  });
 }
  function getCenterLatLngText() {
 return '(' + map.getCenter().lat() +', '+ map.getCenter().lng() +')';
  }
  //This function is the one that I'm not using.
  function centerChanged() {
   centerChangedLast = new Date();
  var latlng = getCenterLatLngText();
  document.getElementById('latlng').innerHTML = latlng;
  document.getElementById('formatedAddress').innerHTML = '';
  currentReverseGeocodeResponse = null;
  }

  function reverseGeocode() {
   reverseGeocodedLast = new Date();
   geocoder.geocode({latLng:map.getCenter()},reverseGeocodeResult);
   }
  //Sets the labels on the HTML
  function reverseGeocodeResult(results, status) {
   currentReverseGeocodeResponse = results;
  if(status == 'OK') {
    if(results.length == 0) {
    document.getElementById('formatedAddress').innerHTML = 'None';
   } else {
     document.getElementById('formatedAddress').innerHTML =       results[0].formatted_address;
    }
    } else {
   document.getElementById('formatedAddress').innerHTML = 'Error';
    }
   }
   //This function is really important it locates the target place
  function geocode() {
  var address = document.getElementById("address").value;
  geocoder.geocode( { "address": address}, 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,
    });

   marker.setMap(map);
   marker.setDraggable(false);

   google.maps.event.addListener(marker, 'dragend', function (event) {
    var point = marker.getPosition();
    map.panTo(point);

    // Update text fields with lat and lng
    document.getElementById("marlat").value = point.lat();
    document.getElementById("marlon").value = point.lng();
   });
  } else {
    alert('Geocode was not successful for the following reason: ' + status);
  }
   });


 var output = document.getElementById("mylatlng");

 //this function shows the user's current position on a label, I'll be merging it with the initialize() function.
 function success(position) {

 var latitude  = position.coords.latitude;
 var longitude = position.coords.longitude;

 output.innerHTML = '<p>Latitude is ' + latitude + '° <br>Longitude is ' +   longitude + '°</p>';
  };

//Error treatment
 function error() {
 output.innerHTML = "Unable to retrieve your location";
 };

 output.innerHTML = "<p>Locating…</p>";

 navigator.geolocation.getCurrentPosition(success, error);
 }
 //This function isn't working yet, it should creat a route from the user's     position to the target place, but I've had no time to fix it.
  function route() {
  // Convert the distance to box around the route from miles to km
  distance = parseFloat(document.getElementById("distance").value) *     1.609344;

  var request = {
    origin: document.pos,
    destination: document.getElementById("address").value,
    travelMode: google.maps.DirectionsTravelMode.DRIVING
  }

  // Make the directions request
  directionService.route(request, function(result, status) {
    if (status == google.maps.DirectionsStatus.OK) {
      directionsRenderer.setDirections(result);

      // Box around the overview path of the first route
      var path = result.routes[0].overview_path;
      var boxes = routeBoxer.box(path, distance);
      drawBoxes(boxes);
    } else {
      alert("Directions query failed: " + status);
    }
  });
}

</script>
</head>

<body onload="initialize()">
Find Place: <input type="text" id="address"/><input type="button" value="Go" onclick="geocode()">
 <div id="map">
<div id="map_canvas" style="width:100%; height:400px"></div>
<div id="crosshair"></div>
</div>

 <table>
<tr><td>Lat/Lng:</td><td><div id="latlng"></div></td></tr>
<tr><td>Address:</td><td><div id="formatedAddress"></div></td></tr>
<tr><td>Zoom Level</td><td><div id="zoom_level">2</div></td></tr>
 </table>
 <table>
<tr><td>Your Coords:</td><td><div id="mylatlng"></div></td></tr>
<tr><td>Your Address:</td><td><div id="myformatedAddress"></div></td></tr>
 </table>
 <table>
<tr><td>Marker Lat:</td><td><div id="marlat"></div></td></tr>
<tr><td>Marker lon:</td><td><div id="marlon"></div></td></tr>
 </table>

</body>
</html>

Thanks in advance, and sorry for the huge code

Try setting your marker position to the same LatLng as your map center and see if it works. One possible reason why marker are not showing up is because part of the code is getting executed before the load event gets fired and the initialize method gets invoked, at that point your map variable is already created but still null.

Here's a code snippet how to show marker:

var map;

function initialize() {

    var mapOptions = {
        zoom: 8,
        center: new google.maps.LatLng(41.056466, -85.3312009),
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

    // Add 1st marker
    var Latlng_0 = new google.maps.LatLng(41.057814980291, -85.329851919709);
    var marker_0 = new google.maps.Marker({
        position: Latlng_0,
        title: "0"
    });

    marker_0.setMap(map);

    //Add 2nd marker
    var Latlng_1 = new google.maps.LatLng(41.065294480291, -85.330151019708);
    var marker_1 = new google.maps.Marker({
        position: Latlng_1,
        title: "1"
    });

    marker_1.setMap(map);
}

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

Here's a related SO ticket which discuss how to show markers: Google maps api marker not showing

  1. Delete setupEvents(); if it does nothing, and even worse, is undefined.
  2. Change "map_canvas" to "map", and change the HTML element id accordingly.
  3. [Optionally] Comment out geocoder line and setMap line. You don't need them.

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