javascript — api google maps добавление маркера на карту, которая уже инициирована

    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 (), которая, когда она вызывается, должна идти, чтобы получить пользовательский lattiude с сервера, использующего 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);
}

1

Решение

Значение, возвращаемое XMLHttpRequest, является строкой. position член google.maps.MarkerOptions объект должен быть 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);
}

доказательство концепции скрипки

фрагмент кода:

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>
1

Другие решения

Других решений пока нет …

По вопросам рекламы [email protected]