简体   繁体   English

google maps 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
    }

So i have this function get_userlat() which when it is called it is suppose to go to get a user lattiude from a server using ajax but when i call this function it dosent do anything when it called. 所以我有这个函数get_userlat(),当它被调用时,它应该去使用ajax从服务器上获取用户lattiude,但是当我调用此函数时,它在调用时不会做任何事情。 I am trying create a tracking code so that your able to track your friends when u enter their pin and user email. 我正在尝试创建跟踪代码,以使您能够在您输入朋友的密码和用户电子邮件时跟踪朋友。 my database has the user lat and lng. 我的数据库有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);
    }

The value returned by the XMLHttpRequest is a string. XMLHttpRequest返回的值是一个字符串。 The position member of a google.maps.MarkerOptions object needs to be a google.maps.LatLng object or a google.maps.LatLngLiteral object. google.maps.MarkerOptions对象的position成员必须是google.maps.LatLng对象或google.maps.LatLngLiteral对象。

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 概念证明

code snippet: 代码段:

 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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM