google 地图 api 将标记添加到已经启动的地图

google maps api adding a marker to map that already initiated

    var watchID;
    var geo;    // for the geolocation object
    var map;    // for the google map object
    var mapMarker;  // the google map marker object
    var markers;


    // position options
    var MAXIMUM_AGE = 200; // miliseconds
    var TIMEOUT = 300000;
    var HIGHACCURACY = true;

    function getGeoLocation() {
        try {
            if( !! navigator.geolocation ) return navigator.geolocation;
            else return undefined;
        } catch(e) {
            return undefined;
        }
    }


    function show_map(position) {
        var lat = position.coords.latitude;
        var lon = position.coords.longitude;
        var latlng = new google.maps.LatLng(lat, lon);
        ajax_post(lat,lon);

        if(map) {
            map.panTo(latlng);
            mapMarker.setPosition(latlng);

        } else {
            var myOptions = {
                zoom: 18,
                center: latlng,

                // mapTypeID --
                // ROADMAP displays the default road map view
                // SATELLITE displays Google Earth satellite images
                // HYBRID displays a mixture of normal and satellite views
                // TERRAIN displays a physical map based on terrain information.
                mapTypeId: google.maps.MapTypeId.ROADMAP

            };
            map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
            map.setTilt(0); // turns off the annoying default 45-deg view

            mapMarker = new google.maps.Marker({
                position: latlng,
                title:"You are here."
            });
            mapMarker.setMap(map);

            alert ('in elses statement after map');
           }
    }
    function geo_error(error) {
        stopWatching();
        switch(error.code) {
            case error.TIMEOUT:
                alert('Geolocation Timeout');
                break;
            case error.POSITION_UNAVAILABLE:
                alert('Geolocation Position unavailable');
                break;
            case error.PERMISSION_DENIED:
                alert('Geolocation Permission denied');
                break;
            default:
                alert('Geolocation returned an unknown error code: ' + error.code);
        }
    }

    function stopWatching() {
        if(watchID) geo.clearWatch(watchID);
        watchID = null;
        alert ('Hey You Said Stop Watching');
    }

    function startWatching() {
        watchID = geo.watchPosition(show_map, geo_error, {
            enableHighAccuracy: HIGHACCURACY,
            maximumAge: MAXIMUM_AGE,
            timeout: TIMEOUT
        });
    }

     function startmap() {
        if((geo = getGeoLocation())) {
            startWatching();
        } else {
            alert('Geolocation not supported.')
        }
    }



    function ajax_post(lat,lon){
    // Create our XMLHttpRequest object
    var hr = new XMLHttpRequest();
    // Create some variables we need to send to our PHP file
    var url = "send/mypostion.php";
    var vars = "postlat="+lat+"&postlon="+lon;
    hr.open("POST", url, true);
    // Set content type header information for sending url encoded variables in the request
    hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    // Access the onreadystatechange event for the XMLHttpRequest object
    hr.onreadystatechange = function() {
        if(hr.readyState == 4 && hr.status == 200) {

            // a string looking like: "32.6986, -117.101" (from a comment)
            var return_data = hr.responseText;
            // alert(return_data);
        }
    }
    // Send the data to PHP now... and wait for response to update the status div
    hr.send(vars); // Actually execute the request
    }

所以我有这个函数 get_userlat() ,当它被调用时,它应该使用 ajax 从服务器获取用户地址,但是当我调用这个函数时,它没有执行当它叫什么。我正在尝试创建一个跟踪代码,以便您在输入他们的密码和用户电子邮件时能够跟踪您的朋友。我的数据库有用户 lat 和 lng。

    function get_userlat(){
    // Create our XMLHttpRequest object
    var hr = new XMLHttpRequest();
    // Create some variables we need to send to our PHP file
    var url = "send/getfriendspostion.php";
    var vars = "postemail="+prompt("What is your friends email")+"&postpin="+prompt("What is your friends pin number");
    hr.open("POST", url, true);
    // Set content type header information for sending url encoded variables in the request
    hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    // Access the onreadystatechange event for the XMLHttpRequest object
    hr.onreadystatechange = function() {
        if(hr.readyState == 4 && hr.status == 200) {
            var return_data = hr.responseText;
            //addMarker(return_data);
            addMarker(return_data);
            return return_data;
        }
    }
    // Send the data to PHP now... and wait for response to update the status div
    hr.send(vars); // Actually execute the request
    }

    function addMarker(location) {
    var markers=new google.maps.Marker({
          position:location,
          });

        markers.setMap(map);
    }

XMLHttpRequest 返回的值为字符串。 google.maps.MarkerOptions object needs to be a google.maps.LatLng object or a google.maps.LatLngLiteral 对象的 position 成员。

hr.onreadystatechange = function() {
    if(hr.readyState == 4 && hr.status == 200) {
        var return_data = hr.responseText;
        //addMarker(return_data);
        addMarker(return_data);
        return return_data;
    }
}

function addMarker(location) {
  // parse the input string into a google.maps.LatLng 
  var coords = location.split(",");
  var position = new google.maps.LatLng(
                       parseFloat(coords[0]), 
                       parseFloat(coords[1])
                     );
  var markers=new google.maps.Marker({
        position:position
      });

  markers.setMap(map);
}

proof of concept fiddle

代码片段:

function addMarker(location) {
  // parse the input string into a google.maps.LatLng 
  var coords = location.split(",");
  var position = new google.maps.LatLng(
    parseFloat(coords[0]),
    parseFloat(coords[1])
  );
  var markers = new google.maps.Marker({
    position: position,
    title: "addMarker"
  });

  markers.setMap(map);
}

var watchID;
var geo; // for the geolocation object
var map; // for the google map object
var mapMarker; // the google map marker object
var markers;

// New York, NY, USA (40.7127837, -74.00594130000002)
// Mountain View, San Diego, CA, USA (32.702723,-117.111768)
var position = {
  coords: {
    latitude: 32.702723,
    longitude: -117.111768
  }
};

function show_map(position) {
  var lat = position.coords.latitude;
  var lon = position.coords.longitude;
  var latlng = new google.maps.LatLng(lat, lon);
  // ajax_post(lat, lon);

  if (map) {
    map.panTo(latlng);
    mapMarker.setPosition(latlng);

  } else {
    var myOptions = {
      zoom: 14,
      center: latlng,

      // mapTypeID --
      // ROADMAP displays the default road map view
      // SATELLITE displays Google Earth satellite images
      // HYBRID displays a mixture of normal and satellite views
      // TERRAIN displays a physical map based on terrain information.
      mapTypeId: google.maps.MapTypeId.ROADMAP

    };
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    map.setTilt(0); // turns off the annoying default 45-deg view

    mapMarker = new google.maps.Marker({
      position: latlng,
      title: "You are here."
    });
    mapMarker.setMap(map);
    addMarker("32.6986, -117.101");
    // alert('in elses statement after map');
  }
}
google.maps.event.addDomListener(window, 'load', function() {
  show_map(position);
});
html,
body,
#map_canvas {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map_canvas"></div>