post Polygon Coordinates (Google Map API v3) to php - javascript

I refer to the question Polygon "Drawing and Getting Coordinates with Google Map API v3" and the code by jhawes which works fine; BUT I've struggle to post the lat/lng-values to a DB using php.
In other scripts with single coordinates I use the following (whereas the variables "BlattNr, Quadrant, MTBlat, MTBlng, Qmlat, Qmlng" are of no interest for that question):
function saveData(BlattNr, Quadrant, MTBlat, MTBlng, Qmlat, Qmlng) {
var latlng = marker.getPosition();
window.location.href = "schritt_2.php?lat=" + latlng.lat() +
"&lng=" + latlng.lng() + "&MTBNr=" + BlattNr + "&Quadrant=" + Quadrant + "&MTBlat=" + MTBlat + "&MTBlng=" + MTBlng + "&Qmlat=" + Qmlat + "&Qmlng=" + Qmlng;
marker.setMap(null);
}
With this I can post the lat and lng of the single point coordinate - but how to pass the multiple lat and lng of various points? I don't know how to define the variable and how to construct the "saveData" function...
Many thanks in advance for any help :-)

Okay, I copy/pasted the code that jhawes put in jsFiddle
I added a few things.
add jQuery
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Save_data
function save_data() {
var data = [];
var len = myPolygon.getPath().getLength();
for (var i = 0; i < len; i++) {
data.push([myPolygon.getPath().getAt(i).lat(), myPolygon.getPath().getAt(i).lng()]);
}
// send data to the server
$.ajax({
url: 'save.php?p=' + JSON.stringify(data),
success: function (message) {
$('#ajaxresponse').html(message);
}
});
}
A button and a display div. Put them somewhere at the bottom of the markup.
<input type="button" onclick="save_data()" value="SAVE">
<div id="ajaxresponse"></div>
Server side: I don't do much here; I'm sure you can handle it.
save.php
<?php
if (isset($_GET['p'])) {
$locations = json_decode($_GET['p'], true);
echo print_r($locations, true) . '<br>';
echo "let's print the second point: lat=" . $locations[1][0] . ", lng=" . $locations[1][0];
}
?>

Related

How to get Dark Sky API to work using mobile gps

I'm trying to build an app using PhoneGap and although I can get the lat and long from my current position using my mobile phone gps, I can't seem to get weather info out of my dark sky api. I don't know what I am doing wrong.
I've tried to use a json script to get the variables lat and long to plug into my api request. There is something I am missing that is needed to bridge the gap.
<script type="text/javascript" charset="utf-8">
// Wait for device API libraries to load
//
document.addEventListener("deviceready", onDeviceReady, false);
// device APIs are available
//
function onDeviceReady() {
navigator.geolocation.getCurrentPosition(onSuccess);
}
// onSuccess Geolocation
//
function onSuccess(position) {
var element = document.getElementById('geolocation');
element.innerHTML = 'Latitude: ' + position.coords.latitude + '<br />' +
'Longitude: ' + position.coords.longitude + '<br />' +
'Altitude: ' + position.coords.altitude + '<br />';
var lat = position.coords.latitude;
var long = position.coords.longitude;
getWeatherData(lat, long)}
}
function getWeatherData(lat, long){
var apiKey = "<my API key>";
var exclude = "?exclude=minutely,hourly,daily,alerts,flags";
var unit = "?units=si";
var url = "https://api.darksky.net/forecast/" + apiKey + "/" + lat + "," + long + exclude + unit;
//get darksky api data
$.ajax({
url: url,
dataType: "jsonp",
success: function (weatherData) {
//weather description
var description = weatherData.currently.summary;
$('#weather-description').text(weatherData.currently.summary);
}
});
print(getWeatherData)
}
function print(getWeatherData){
var element = document.getElementById('weather-description');
element.innerHTML = 'Description ' + weatherData.currently.summary + '<br />';
}
</script>
Then in my HTML...
<p id="geolocation">Finding geolocation...</p>
<p id="weather-description">Loading Description...</p>
Actual results, lat and long and altitude are displayed instead of Finding geolocation, but I expected the weather description to be printed where it says Loading description but it is not.
I worked. Thank you to NewToJS for helping me. The problem was I wasn't calling the function. I've been working on this for 4 days I can't believe it works!

I'm having issues with an API

I'm having issues with getting this API to work.
I have used the same code with Google Finance API and that works perfectly. The issue is that I can only get a small amount of stocks out, and in the long run, I need to run 12000 stocks through (if possible).
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
var temp = [];
$(document).ready(function(){
stockInformation();
setInterval(stockInformation, 5000);
});
function stockInformation()
{
$.ajax({
url:"https://api.website.com/public/user/token/stock/SDRL/quote",
dataType:"jsonp",
jsonp:"callback",
jsonpCallback:"quote"
});
var i = 0; var j = 0;var status = "";
quote = function(data){
var output = "<table>"
$.each(data, function(key, value){
if (value.l_cur > temp[j])
status = "<td style=color:green>Up</td>";
else if (value.l_cur < temp[j])
status = "<td style=color:red>Down</td>";
else
status = "<td>Same</td>";
j++;
output += "<tr><td>" + value.t + "</td><td>" + value.l_cur + "</td>" + status + "</tr>";
temp[i] = value.l_cur;i++;
})
output += "</table>";
$("#result").html(output);
}
}
</script>
<div id="result"></div>
This is what the API returns (not with the code above):
{"timestamp":"1503691321","datetime":"2017-08-25 16:02:01 (UTC)","price":"6.17","price change":"0.12","price pct change":"1.98","open":"6.09","volumn":"1852887","low":"6.00","high":"6.22","currency":"USD"}
Many of googles api's limit the number of requests you can make in a given amount of time. Sometimes even as low as 50 per month depending on the api and the type of request. Its doesn't look like there is anything wrong with the way you are using the api in your code.
You could get around that though potentially by paginating. Start with like 30 at a time then when your user clicks a next button or scrolls to the end of the page then go get the next 30.

Pass json value as a variable outside the function [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
I'm working on how to push the value of a variable outside a json function. I'm integrating Google maps and Instagram's API together so I'm passing the longitude and latitude coordinates to glat and glng to var url (which is outside the google function. Currently I'm using PHP and not really familiar with json.
var glat;
var glng;
//Google maps latitude and coordinates
$.getJSON(mapurl, function(google){
glat = google.results[0].geometry.location.lat;
glng = google.results[0].geometry.location.lng;
console.log('<?php echo urlencode($_GET['location']);?>');
console.log(glat);
console.log(glng);
//return glat;
});
var url = "https://api.instagram.com/v1/media/search?lat=" + glat + "&lng=" + glng + "&distance=1000&client_id=<?php echo $client_id; ?>&count=40&callback=?";
//This pulls the instagram images
console.log(url);
//Instagram Feed
$.getJSON(url, function (response) {
//http://techmonks.net/instagram-using-the-api/
for(var i = 0; i < 40; i++){
$("#feed ul").append("<li><a target='_blank' href='"+response.data[i].link +"'><img src='"+response.data[i].images.low_resolution.url+"'/></a></li>");
}
});
$.getJSON causes an asynchronous XMLHttpRequest. Since this is asynchronous, lat and lng are not defined when you try to define your URL to point to Instagram.
var glat;
var glng;
//Google maps latitude and coordinates
$.getJSON(mapurl, function(google){
glat = google.results[0].geometry.location.lat;
glng = google.results[0].geometry.location.lng;
console.log('<?php echo urlencode($_GET['location']);?>');
console.log(glat);
console.log(glng);
var url = "https://api.instagram.com/v1/media/search?lat=" + glat + "&lng=" + glng + "&distance=1000&client_id=<?php echo $client_id; ?>&count=40&callback=?";
console.log(url);
$.getJSON(url, function (response) {
//http://techmonks.net/instagram-using-the-api/
for(var i = 0; i < 40; i++){
$("#feed ul").append("<li><a target='_blank' href='"+response.data[i].link +"'><img src='"+response.data[i].images.low_resolution.url+"'/></a></li>");
}
});
});

Retrieve XML Data to use webpage

What I am trying to do:
Get location based off of IP (Done)
Use the City and Country code to use openweather's API (Done)
Read the XML into my webpage so that I can display the "Temperature" field.
This is my first venture into using XML in webpages, and I've tried for 3 days now with no success. I have searched google and stackoverflow, and have tried many things so far, including SimpleXMLElement, with no luck.
What I currently have on my page is just a generated link to the XML sheet for your location.
<script language="JavaScript" src="http://j.maxmind.com/app/geoip.js"></script>
<script language="JavaScript">
var country = geoip_country_code();
var city = geoip_city();
document.write('Link text');
</script>
How am I able to display the text from the required field on my page?
Thanks in advance! :)
It might be easier to change the API call to return JSON, in which case you could then use this code, the temps are stored in temp, temp_min and temp_max.
var country = geoip_country_code();
var city = geoip_city();
$.getJSON('http://api.openweathermap.org/data/2.5/weather?q=' + city + ',' + country + '&mode=json&units=metric', function( json ) {
var temp = json.main.temp;
var temp_min = json.main.temp_min;
var temp_max = json.main.temp_max;
document.write( 'Temp: ' + temp + '<br>');
document.write( 'Temp Min: ' + temp_min + '<br>');
document.write( 'Temp Max: ' + temp_max + '<br>');
});
You could use javascript library to convert the xml into a javascript object - one such library is called xml2json, it works as a jQuery plugin: http://www.fyneworks.com/jquery/xml-to-json/
Then you can simply do:
var xmlObject;
$.ajax({
url: url_of_xml,
success: function(data) {
xmlObject = $.xml2json(data);
}
});
Then you just need to place the data on your page. The object in my example is faked, but it gives you the idea:
// put this line in the success callback of your ajax call
// after you create the xmlObject
$('#temp').html(xmlObject.weather.temp);
To display the temperature you get the XML, and read one of the three temperature attributes from the XML returned:
$.get("http://api.openweathermap.org/data/2.5/weather?q=' + city + ',' + country + '&mode=xml&units=metric", function(xml) {
avg = $(xml).find("temperature").attr("value"));
max = $(xml).find("temperature").attr("max"));
min = $(xml).find("temperature").attr("min"));
(using JQuery)

JQuery $.each returning same data set twice

I'm building an Instagram mapping app and I'm trying to iterate through the returned JSON using $.each. I'm currently testing it by returning the coordinates of the picture into a <div>. It's working wonderfully, except the same data shows up twice. Here is the statement (the commented-out code is for putting it on the map):
$.each(photos.data, function (index, photo) {
if (photo.location) {
/* var photocoords = google.maps.LatLng(photo.location.latitude,location.longitude);
var marker = new google.maps.Marker({
position: photocoords,
map: map,
title: 'Test'
});//end new marker
*/
photo = photo.location.latitude + ' , ' + photo.location.longitude + '<br>';
$('#photos-wrap').append(photo);
} //end if
else {
return true
}
});
And the data it's returning:
38.9232268 , -77.0464289
35.046506242 , -90.025382579
35.189142533 , -101.987259233
38.9232268 , -77.0464289
35.046506242 , -90.025382579
35.189142533 , -101.987259233
Thanks for any help you can provide.
change your code to this one
var new_photo = photo.location.latitude + ' , ' + photo.location.longitude + '<br>';
$('#photos-wrap').append(new_photo);

Categories