why Geocoder google doesn't want to recognize more addresses? - php

I have one array with coordinates (lat, long)...
This array has about 60-80 items...
In my foreach cycle there are...
...{
$lat = substr($xx[1],0,8);
$long = substr($xx[0],0,8);
?>
<script type="text/javascript">
// <![CDATA[
$(function() {
var geocoder = new google.maps.Geocoder();
function geocodePosition(pos,pos2) {
geocoder.geocode({
latLng: new google.maps.LatLng(pos,pos2)
}, function(responses) {
if (responses && responses.length > 0) {
console.log(responses[0].formatted_address);
} else {
console.log('Cannot determine address at this location.');
}
});
}
geocodePosition(<?php echo $lat ?>,<?php echo $long ?>);
});
// ]]>
</script>
<?php } ...
Geocoder geocodes at the most 5 coordinates, others come with output 'Cannot determine address at this location.'
When I take some of those, which "could not be determined", I use them manually (just 1 item = lat and long, not the whole array) it works.
So where's the problem?

You cant request addresses too fast in a row (blocked by google), you need to use small setTimeout() between when doing it inside loop. Also note that you can request only 2500 addresses per day with basic api, with business over 100000 source from google.
How to avoid google map geocode limit
Setting timeout to simulate pause
Geocode markers from PHP array
Avoid geocode limit - js / html source

Related

How to move marker on a map with mapbox api using json and php?

I'm using mapbox api to display maps and directions. It's easy and it works well. I want to know how to update a marker's location on the map without refreshing a page. I read this page and this page in their documentation. I understand their examples but I'm not fully grasping how to implement realtime data in my codes without causing the page to refresh. Right now I have a script that updates the user location in the database every 15 seconds and returns longitude, latitude. I have the data now what? This is where I get highly confused. If you can help I would really appreciate. I have stripped down the codes for the sake of this question.
map.html
<script type="text/javascript" src="js/jquery.min.js"></script>
<script src="https://api.mapbox.com/mapbox-gl-js/v1.7.0/mapbox-gl.js"></script>
<link href="https://api.mapbox.com/mapbox-gl-js/v1.7.0/mapbox-gl.css" rel="stylesheet" />
<script type="text/javascript" src="geolocation.js"></script>
<!--Display map-->
<div id="map"></div>
<!--mapbox script-->
<script>
mapboxgl.accessToken ='pk.xxxxxxxx';
var map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/streets-v11',
center:[$longitude,$latitude],
zoom: 15
});
var geojson = {
type: 'FeatureCollection',
features: [{
type: 'Feature',
geometry: {
type: 'Point',
coordinates:[$longitude,$latitude]
},
properties: {
title: '',
description: ''
}}]
};
geojson.features.forEach(function(marker) {
var el = document.createElement('div');
el.className = 'marker';
new mapboxgl.Marker(el)
.setLngLat(marker.geometry.coordinates)
.setPopup(new mapboxgl.Popup({ offset: 25 })
.setHTML('<h3>' + marker.properties.title + '</h3><p>' + marker.properties.description + '</p>'))
.addTo(map);
});
</script>
geolocation.js
setInterval(function () {
$.get("https://ipinfo.io", function (response) {
//variables
var user_id = $('.userid').val();
var geoLocation = response.loc;
//build array
var values ='geoLocation=' + encodeURIComponent(geoLocation)
+ '&userid=' + encodeURIComponent(user_id);
$.ajax({
type: 'POST',
url: 'https://mywebsite.com/mobile/geolocation.php',
data: values,
success: function (data) {
//returns new longitude
var lon = data.longitude;
//returns new latitude
var lat = data.latitude;
}
});
}, "jsonp");
}, 15000);
geolocation.php
$geoLocation= mysqli_real_escape_string($conn,$_POST['geoLocation']);//coordinates
$userid= mysqli_real_escape_string($conn,$_POST['userid']);//userid
//split coordinates into lat and longitude
$longitude = substr($geoLocation, strpos($geoLocation, ",") + 1); //put it first
$latitude =preg_replace('/^([^,]*).*$/', '$1', $geoLocation); // put it second
//insert new coordinates
$insertgeo = $conn->prepare("INSERT INTO user_geolocation (latitude,longitude,userid) VALUES(?,?,?)");
$insertgeo->bind_param("sss",$latitude,$longitude,$userid);
$insertgeo->execute();
$insertgeo->close();
//return answer to json
$result = array('message' => 'success',
'userid'=>$userid,
'longitude'=>$longitude,
'latitude'=>$latitude);
header('Content-Type: application/json');
echo json_encode($result);
The documentation resources you've linked are helpful, but I think this add live realtime data example is even better for your use case. If you zoom out of the map to see a larger region of the world, you will see a blue rocket icon marker which moves every two seconds without refreshing the page. In essence, this is exactly what you're looking to do! I'll explain how the example is working so that you can use the same logic to update your own marker locations without refreshing the page as well.
The rocket icon in this example is added to the map with a source and layer. The source specifies all the underlying data (in this case, the updating GeoJSON served by the https://wanderdrone.appspot.com URL), and the layer specifies how that data should be styled on the map. If you visit this URL, you'll see that the coordinates update each time you refresh the page.
So, the code below:
Gets the GeoJSON from the url every 2 seconds.
Gets the map's 'drone' source using Map#getSource.
Sets the data used by the source in (2) to be the GeoJSON at the url using Map#setData.
window.setInterval(function() {
map.getSource('drone').setData(url);
}, 2000);
Your current implementation is using HTML-based markers via GL JS's Marker component. So, instead of switching to this source-and-layer based approach outlined above, you could use the Marker#setLngLat method each time the user's location updates in your database. This also will not refresh the whole page.

About ajax post data to PHP

I'm newbie to Ajax, I know when I want to pass data to PHP file I need to use Ajax, but I not sure the Ajax can use like what I coded. If can't, anybody can help me on this? Cause I want to use the html5 geolocation to get the user location. I tried geoplugin before but the IP I get always is the server IP not the user IP, I got try to ask here for the geoplugin but no work. I have tried this html5 geolocation to display my lon and lat, it is correct one, but I want to pass the variable to another PHP file for calculate the nearest distance with data get from MySQL.
In index.php
<script>
$(document).ready(function(){
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showLocation);
} else {
$('#location').html('Geolocation is not supported by this browser.');
}
});
function showLocation(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
$.ajax({
type:'POST',
url:'index1.php',
data:'latitude='+latitude+'&longitude='+longitude
}
});
}
</script>
In index1.php
<?php
session_start();
$link=mysqli_connect("localhost","id2135226_ukwai1203","ukwai1203");
mysqli_select_db($link,"id2135226_demo");
$lat=$_POST['latitude'];
$lon=$_POST['longitude'];
$sql = "select branch_id,(6371 * 2 * ASIN(SQRT( POWER(SIN(($lat -
branch_lat)*pi()/180/2),2)+COS($lat*pi()/180
)*COS(branch_lat*pi()/180)*POWER(SIN(($lon-branch_lon)*pi()/180/2),2))))
as
distance From Branch ORDER BY distance ASC LIMIT 1";
$res=mysqli_query($link,$sql);
while($row=mysqli_fetch_array($res)){
$_SESSION['location']=$row['branch_id'];
?>
<script>
window.location="http://ukwai1203.000webhostapp.com/fyp/user/shop.php";
</script>
<?php
}
?>
change your code to this:
function showLocation(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
$.ajax({
method:"POST",
url:"index1.php",
data:{
latitude : latitude,
longitude : longitude
}
});//ajax end
}//function end
Consider using IDE like eclipse to help you spot missing brackets etc.
And when working by modifying old code check libraries versions like jquery version.

Send a request to a php page and then get back results using ajax

I have a script where i am trying to send some location information to a php page, carry out a mysql search query and get the results back without going to another page.
my php works fine, and i have had the page working that it redirects to the php page, however when i try and use the code below, i do not get any results passed back.
Javascript code
function phpRedirect(loc) {
// var radius = get('r'); // Retrieve GET values for search radius and
// var numResults = get('n'); // number of results
var radius = 10; // Retrieve GET values for search radius and
var numResults = 5; // number of results
var latitude = loc.coords.latitude; // Get long, lat and accuracy from
var longitude = loc.coords.longitude; // location object
var accuracy = loc.coords.accuracy;
var xmlHttp = new XMLHttpRequest(); //not the cross browser way of doing it
xmlHttp.open("GET", "find.php?lat=" + latitude + "&long=" +
longitude + "&acc=" + accuracy + "&r=" + radius
+ "&n=" + numResults, true);
xmlHttp.send(null);
}
$(function ()
{
$.ajax({
url: 'find.php', //the script to call to get data
type: "post",
data: { getData: true },
dataType: 'json', //data format
success: function(data) //on recieve of reply
{
var name = data[0];
$('#output').html("<b>username: </b>"+username);
}
});
});
function error(loc) {
// This is called if the location can't be found.
document.write("Error finding GPS location");
}
// Use navigator to get current user location. If found, calls 'phpRedirect()',
// If not available calls 'error()'. Includes timeout and ensures highest acc.
navigator.geolocation.getCurrentPosition(phpRedirect, error, {maximumAge:60000, timeout:5000, enableHighAccuracy:true});
<div id="output">this element will be accessed by jquery and this text replaced </div>
Below is the output from my php query,
$result=mysql_query($query) or die (mysql_error());
while($row=mysql_fetch_assoc($result)) $data[]=$row; // Turn result to array
$acc_package = array('location_accuracy'=>"$accuracy"); // Include result array
$output[] = $acc_package; // and accuracy value inside
$output[] = $data; // an output array.
print(json_encode($output)); // Convert output array to json format and print
Which gives the following results
[{"location_accuracy":"122000"},[{"username":"bobbyj","distance":"0.484367160806139"}]]
Sam, I have a few suggestions for you.
First, the jQuery library is great and the AJAX module works amazing :) It's great that you are using it! No need to mix that old XMLHTTP junk with it (they do basically the same thing). So get rid of that and replace it with jQuery ajax.
Let's start with something really basic:
$.ajax({
url: 'find.php',
type: "POST",
data: { lat: lattitude }
}).done(function( msg ) {
alert(msg);
});
Put your other variables in the data: as well.
On your PHP page, try a simple var_dump($_POST); so you can see what is coming through. The AJAX should make an alert with contents of the PHP page.
Work your way up from this with your Mysql :)

Google Maps API and PHP

I have this code
http://jsfiddle.net/DanielMontenegro/7pdU4/3/
Now, supose that I want to put that map in a site to allow people to report some particular event through the geocoding service. I would like to ask how could I manage to get the address/coordinates of that event in a table, and gatherall the users reports into a single database.
There is a lot of goood information about interfacing the Google Maps API v3 with PHP/MySQL in the "Articles" section of the documentation
This one looks like it answers your question; From Info Windows to a Database: Saving User-Added Form Data
See below code and try it.
I am using php static array you can connect your database and create array according your requirement. see the array below.
<?php $item = array('jaipur, rajasthan,india', 'udaipur, rajasthan,india'); ?>
Below My Code Take a look.
<html>
<head>
<script src="http://maps.google.com/maps?file=api&v=2&key=AIzaSyDwFjOazEAe1MI7nHV6vUwkWytOp8LH2Zk" type="text/javascript"></script>
</head>
<body onload="initialize();">
<?php $item = array('jaipur, rajasthan,india', 'udaipur, rajasthan,india'); ?>
<script>
var map = null;
var geocoder = null;
function initialize() {
if (GBrowserIsCompatible()) {
map = new GMap2(document.getElementById("map_canvas"));
var addresses = ["<?php echo implode ('","', $item); ?>"]
var geocoder = new GClientGeocoder();
//var addresses = ["A II Z, Ibn Battuta Mall, Sheikh Zayed Road, 5th Interchange, Jebel Ali Village, Dubai","A. Testoni,Dubai Festival City Mall, Ground Floor, Dubai", "Abdulla Hussain Khunji, The Dubai Mall,Downtown, Abu Dhabi"];
var curIndex = 0;
function showAddress() {
var _cur = addresses[curIndex];
geocoder.getLatLng(
_cur,
function(point) {
if (!point) {
//alert(_cur + " not found");
//map.setCenter(new GLatLng(0, 0), 6);
//map.setUIToDefault();
} else {
//console.log(_cur+":"+point);
//alert(_cur);
var cafeIcon = new GIcon(G_DEFAULT_ICON);
// Set up our GMarkerOptions object
markerOptions = { icon:cafeIcon };
map.setCenter(point, 6);
var marker = new GMarker(point, markerOptions);
map.addOverlay(marker);
var sales = new Array();
sales = _cur.split("|");
//Add click event on push pin to open info window on click of the icon
GEvent.addListener(marker, "click", function() {
marker.openInfoWindowHtml("<p class='para1bold' style=\"font-weight: bold;\">Address <br /><span class='para1' style='font-weight:normal;'>" + sales[1] + "</span></p>");
});
//Provides map,satellite,hybrid and terrain views in the map along with zoom control
map.setUIToDefault();
}
//do next after done
curIndex++;
if(curIndex<addresses.length)
showAddress();
}
);
}
showAddress();
}
}
</script>
<div id="map_canvas" style="width:100%; height:750px;"></div>
</body>
</html>
You'll need to set up an action listener of some kind (preferably a listener that will listen for a user click on the map). Then, simply geocode the resulting lat/lng and store what you receive in your table.
User clicks a point on map.
Click event grabs what lat/lng the user clicked on.
The Lat/lng is geocoded for a textual address using Ajax.
Both Lat/lng and textual address are stored side-by-side in your database table.

using the google maps API - marker cluster

I really am a JS noob - I have never really used itbefore and am struggling using the marker clusterer google provide. I have rad the documentation
here is the code
<script src="http://localhost/wheredidmytweetgo/js/markercluster.js" type="text/javascript"></script>
<script type="text/javascript">
//<![CDATA[
function load() {
if (GBrowserIsCompatible()) {
var map = new GMap2(
document.getElementById("map"));
map.addControl(new GSmallMapControl());
map.setCenter(
new GLatLng( 56.65622649350222, -19.86328125), 2);
var mc = new MarkerClusterer(map);
function createMarker(point, text, title) {
var marker =
new GMarker(point,{title:title});
GEvent.addListener(
marker, "click", function() {
marker.openInfoWindowHtml(text);
});
return marker;
}
<?php
foreach ($cluster_location as $location) {
?>
var marker = createMarker(
new GLatLng(<?php echo $location ?>),
'Marker text <?php echo $location ?>',
'Example Title text <?php echo $location ?>');
map.addMarker(marker);
<?php }
?>
}
}
cluster location is just an array of lat and longs - My code is working fine when just using the add.overlay however there are too many to make the map readable hence the need for clustering. I do load the clustering JS which I have I have included.
I create the clusterer object and pass in map as defined.
var markers = [];
//create array
I know I can create a JS array and pass this in to
var mc = new MarkerClusterer(map, markers);
But I simply dont have the JS knowledge to create an array at this time (I intend to learn) and the Google documentation advises you can iterate and add one at a time using addMarker
Hi Tom - Thanksfor the info - I have tried doing what you advised and have came up with the below:
<script src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" src="http://localhost/wheredidmytweetgo/js/markercluster.js">
</script>
<script type="text/javascript">
function initialize() {
var center = new google.maps.LatLng(37.4419, -122.1419);
var map = new google.maps.Map(document.getElementById('map'), {
'zoom': 13,
'center': center,
'mapTypeId': google.maps.MapTypeId.ROADMAP
});
var markers = [];
<?php foreach ($cluster_location as $location) { ?>{
var marker = new google.maps.Marker({'position': <?php echo $location;?>});
markers.push(marker);
}
<?
}
?>
var markerCluster = new MarkerClusterer(map, markers);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<h3>A simple example of MarkerClusterer (100 markers)</h3>
<p>
Compiled |
Standard version of the script.
</p>
<div id="map-container"><div id="map"></div></div>
</body>
</html>
But my map still loads empty. I'm using literally the most basic google provided code now and just loading my own markers in. I know my markers positioning should be okay because when I go to view my page source I can see
{
var marker = new google.maps.Marker({'position': 40.0994425,-74.9325683});
markers.push(marker);
});
for each marker. any more help would really be appreciated!
Please check the examples on google maps utilities library page (link).
But basically to add instance of an object (a marker) to an array you have to define the array first so you need to do the var markers = []; above the loop where you create the markers. And then as you create the markers you have to add them to the markers array by calling the push method of an array (while you are at it go to MDN and read about arrays! if you want to learn it's good time to start there - there is a tutorial about JS there as well (link).
So inside of the foreach loop afer you've defined a marker just add it to the array markers.push(marker); This will make the markers available for the MarkerCluster initialization.
In a longer term when you figure out javascript a bit better you'll probably want to replace this part with either passing data as JSON object to the DOM so methods can handle it or even better - have the data for markers be retrieved with ajax query. But one step at a time I guess :)
Maybe try the fun interactive tutorials at the www.codecademy.com? They are quite basic but seems like that's exactly what you need
EDIT:
var marker,
markers = [];
<?php foreach ($cluster_location as $location) { ?>
marker = new google.maps.Marker({'position': <?php echo $location;?>});
markers.push(marker);
<? } ?>

Categories