Geocoding by extracting location from MySQL via PHP - javascript

I have written the following PHP script to get the value from MySQL database:
<?php
$user="root";
$password="password";
$dbh = new PDO("mysql:host=localhost;dbname=muzicmap", $user, $password);
$sql = "SELECT DISTINCT (
`name`
) AS `name` , `id` , `location` , `background` , `genre` , `current_members` , `website` , `image` , `lonlat`
FROM `artist`
WHERE `location` LIKE '%Los Angeles%'
LIMIT 10
";
$result = $dbh->query($sql)->fetchAll(PDO::FETCH_ASSOC);
//To output as-is json data result
//header('Content-type: application/json');
//echo json_encode($result);
//Or if you need to edit/manipulate the result before output
foreach ($result as $row){
$return[]=array('id' => $row['id'],'name'=>$row['name'],'location'=> $row['location'],'background' => $row['background'], 'genre' => $row['genre'],'current_members'=>$row['current_members'],'website' => $row['website']);
}
$dbh = null;
header('Content-type: application/json');
echo json_encode($return);
?>
Now I have made a page in which I want to achieve 3 things:
1. Geocode the location in the location field of my json.
2. Put markers on google maps.
3. Make a drawable type object after doing this all.
So I wrote the following:
markers= []
var geocoder;
function initialize() {
var mapOptions = {
zoom: 4,
center: new google.maps.LatLng(40.2859268188,-75.9843826294)
}
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
var drawingManager = new google.maps.drawing.DrawingManager({
drawingMode: google.maps.drawing.OverlayType.MARKER,
drawingControl: true,
drawingControlOptions: {
position: google.maps.ControlPosition.TOP_CENTER,
drawingModes: [
google.maps.drawing.OverlayType.CIRCLE,
]
},
circleOptions: {
fillColor: '#FFFF00',
fillOpacity: 0,
strokeWeight: 1,
clickable: false,
editable: true,
zIndex: 1
}
});
drawingManager.setMap(map);
google.maps.event.addListener(drawingManager, 'circlecomplete', function(circle) {
var IDs=[];
for(var k in markers){
if(google.maps.geometry.spherical
.computeDistanceBetween(circle.getCenter(),markers[k].getPosition())
<=circle.getRadius()){
IDs.push(k);
}
}
});
$(function ()
{
$.ajax({
url: 'jsonTest.php', //the script to call to get data
data: "",
dataType: 'json',
success: function(data)
{
adMarker(map, data);
}
});
});
}
function adMarker(map,json1){
geocoder= new google.maps.Geocoder();
for (var i = 0; i < (json1.length); i++) {
geocoder.geocode({'address':json1[i]['location']},function(results,status){
if (status == google.maps.GeocoderStatus.OK){
var marker = new google.maps.Marker({
position: results[0].geometry.location,
map: map,
title: json1[i]['names'],
zIndex: json1[i]['id']
});
markers.push(marker);
}else {
alert("Something wrong");
}
});
}
}
google.maps.event.addDomListener(window, 'load', initialize);
I am not getting the desired result where the markers are put on the map after geocoding. When I debug it I see that the code snipet which is supposed to geocode and create the marker is not run in the for iteration. Why is that? I am new to javascript I would really appreciate all the help fixing this.
The error in the debugger though,says:
InvalidValueError: setZIndex: not a number

I solved the problem.
Because there is an asynchronous call in the adMarker(). I made a function so that copies of that function are made on each for iteration as the asynchronous call will run only after the iteration is complete. This way all the iteration with copies will run. Updated code:
function adMarker(map,json1){
geocoder= new google.maps.Geocoder();
for (var i = 0; i < (json1.length); i++) {
abc(i, json1, map);
}
}
function abc (index, json1, map){
var current_index = index;
geocoder.geocode({'address':json1[index]['location']},function(results,status){
if (status == google.maps.GeocoderStatus.OK){
var marker = new google.maps.Marker({
position: results[0].geometry.location,
map: map,
title: json1[index]['names'],
zIndex: parseInt(json1[index]['id'])
});
markers.push(marker);
}else {
alert("Something wrong");
}
});
}

Related

Add a space after comma in an array

I have a PHP code giving back an array
<?php
$sql5 = "SELECT * FROM Building";
$result5 = $connect->query($sql5);
$emparray = array();
while($row5 = $result5->fetch(PDO::FETCH_ASSOC)) {
$coordLat = floatval($row5['Building_lat']);
$coordLng = floatval($row5['Building_lng']);
$emparray[] = array( $row5['Building_name'] , $coordLat , $coordLng , $row5['Building_period'] );
}
$jsonstring= json_encode($emparray);
?>
output from $jsonstring is
[["Hotel Montgomery",50.85000000000000142108547152020037174224853515625,4.339999999999999857891452847979962825775146484375,"June"]]
I need to use these array to put markers on a Google Map.
That's where JavaScript enter the game.
markers1 = <?php echo $jsonstring; ?>;
function initialize() {
var center = new google.maps.LatLng(50.85,4.34);
var mapOptions = {
zoom: 13,
center: center,
disableDefaultUI: true,
styles: noPoi
};
map = new google.maps.Map(document.getElementById('map'), mapOptions);
for (i = 0; i < markers1.length; i++) {
addMarker(markers1[i]);
}
}
function addMarker(marker) {
var category = marker[4];
var title = marker[1];
var pos = new google.maps.LatLng(marker[2], marker[3]);
var content = marker[1];
marker1 = new google.maps.Marker({
title: title,
position: pos,
category: category,
map: map
});
gmarkers1.push(marker1);
google.maps.event.addListener(marker1, 'click', (function (marker1, content) {
return function () {
console.log('Gmarker 1 gets pushed');
infowindow.setContent(content);
infowindow.open(map, marker1);
map.panTo(this.getPosition());
map.setZoom(15);
}
})(marker1, content));
}
Problem is, I need to add a space after the comma of each array in order to make it work. Otherwise, the coordinates doesn't work.
If I write it manually (without the echo, adding space), it's working. Of course these array come from an SQL query and I need an echo to get all datas.
If I get it right, what you need is join your array, transform into a string with a particular pattern. Try echo join(", ", $emparray); if matches your case then just use this return in a variable instead of your $jsonstring.

using mysql and php with google maps

I'm trying loop through every row in a table and set a marker using the value provided in the "address column". The js code and the php code until setMarker() works fine but I'm not sure how to go about using the function inside php code.
<?php
require 'private/database.php';
$sql = "SELECT * FROM form;";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo '<script>setMarker($row["address"]);</script>';
}
} else {
echo '<script>console.log("ERROR: marker database empty");</script>';
}
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 15,
center: {lat: 24.149950, lng: 120.638610},
mapId: '63d22d3ae6cf15ff'
});
}
// geocoder
function setMarker(address) {
const geocoder = new google.maps.Geocoder();
geocoder.geocode({address: address, componentRestrictions: {
country: 'TW'}}, (results, status) => {
if (status === 'OK') {
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert(`Geocode unsuccessful for address: "${address}"\nSTATUS CODE: ${status}`);
}
});
}
This is more or less what I meant with the comment I made - this way the map is created by the initMap callback function before any attempts to create the markers is made - which might not be the case in the original. This is quickly put together and not tested.
<script>
var map;
<?php
require 'private/database.php';
$sql = "SELECT * FROM form;";
$result = mysqli_query($conn, $sql);
$data=array();
while ($row = mysqli_fetch_assoc($result)) {
$data[]=$row;
}
// create the js variable
printf(
'var json=%s;',
json_encode( $data )
);
?>
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 15,
center: {lat: 24.149950, lng: 120.638610},
mapId: '63d22d3ae6cf15ff'
});
Object.keys(json).forEach( key => {
let obj=json[ key ];
setMarker( obj['address'] )
})
}
function setMarker(address) {
const geocoder = new google.maps.Geocoder();
geocoder.geocode( { address: address, componentRestrictions: { country: 'TW'} }, (results, status) => {
if (status === 'OK') {
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert(`Geocode unsuccessful for address: "${address}"\nSTATUS CODE: ${status}`);
}
});
}
</script>

Javascript & PHP show multiple trackers in Google Maps API

Currently, I'm developing a system that will bring all latitude and longitude from MySQLi DB, and will output every data on the page. Here is my PHP code (working without any problem):
header('Content-Type: text/html; charset=utf-8');
require('database.php');
$query = mysqli_query($mysqli, "SELECT * FROM `tracking`");
if (!$query)
{
die('Error: ' . mysqli_error($mysqli));
}
if(mysqli_num_rows($query) > 0){
$getList = array();
while ($row = mysqli_fetch_assoc($query)) {
$getList[] = $row;
}
for($i = 0, $l = count($getList); $i < $l; ++$i) {
echo $getList[$i]['lat'].",".$getList[$i]['lon']."\n";
}
}
e.g output: -71.99991299555996,-83.18116602 -22.809918399999997,-43.4211132 -22.8540416,-43.2488448
Now, I need bring all data and put into an array, and put whole latitude/longitude to markers in Google Maps. Check what I have tried:
var check = false;
function refreshAll() { // This function will be called every 60 seconds
var locations = [];
locations.length = 0;
$.ajax({
type: "GET",
url: "show.php",
success: function(x)
{
var items = x.split("\n");
for(i=0; i<items.length; i++){
var data = items[i];
if ((items[i]).length > 1) {
locations.push(items[i].trim());
}
}
if (check == false) { // this will avoid map refreshing, I need only markers update.
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 2,
center: new google.maps.LatLng(-33.92, 151.25),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
check = true;
}
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < locations.length; i++) {
alert(locations[i]);
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i].trim()),
map: map
});
}
}
});}
The problem is: the markers is not being set, and have no errors in console. I'm working on this in the last two days and can't find any solution. Can you help me? Thank you.
As you can see here in the docs, the LatLng object is different than the one you are using.
So, replace:
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i].trim()),
map: map
});
With
locations[i] = locations[i].trim().split(',');
var latLng = {lat: Number(locations[i][0]), lng: Number(locations[i][1])};
marker = new google.maps.Marker({
position: latLng,
map: map
});
Check out, the map object is in your infoWindow variable, try to set there the positions.
This should be used inside the locations loop.
var pos = {
lat: latitude,
lng: longitude
};
infoWindow.setPosition(pos);

How to update map data throug ajax

I am trying to update map data through ajax but ist's not working here is my code:
$(document).ready(function() {
function makeRequest(){
$.ajax({
url:"<?php echo Url::base(true).'/users/online-peoples'; ?>",
type:"POST",
})
.done(function(result){
var icon1 = 'https://mt.googleapis.com/vt/icon/name=icons/onion/27-cabs.png&scale=1.0';
if(result){
var map;
function initMap() {
var infowindow = new google.maps.InfoWindow();
var mapOptions = {
zoom: 12,
center: new google.maps.LatLng('30.7333','76.7794'),
mapTypeControlOptions: {
mapTypeIds: ['roadmap']
}
};
var map = new google.maps.Map(document.getElementById('map'), mapOptions);
var online =result;
var mapIcons = ['https://mt.googleapis.com/vt/icon/name=icons/onion/27-cabs.png&scale=1.0'];
var person = {3:"Customer1 : ", 4:"Driver1 : "};
var arr = [];
var marker, i;
for (i = 0; i < online.length; i++)
{
console.log(online[i]);
arr.push(new google.maps.LatLng(online[i][0], online[i][0]));
marker = new google.maps.Marker({
position: new google.maps.LatLng(online[i][0], online[i][1]),
icon:mapIcons[0],
suppressMarkers: true,
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(person[online[i][4]]+online[i][2]+', Phone : '+online[i][5]);
infowindow.open(map, marker);
}
})(marker, i));
}
}
}
});
}
setInterval(makeRequest, (10 * 1000));
});
The above code update map icons and date every 10 secondas but it's not working.Where i am doing wrong ?
This is my data :
[
["30.740395","76.7804482","Dbd Dbdhdh","1",4],
["30.740395","76.7804482","Sam Sam","1",4],
["30.7404344","76.7804032","Sumit Kumar","1",4],
["30.74041018","76.78060575","Chetan Nagrath","3",4],
["30.7403555","76.7804933","Sahil Kapoor","2",4],
["30.7403648","76.7805835","paras kumar",1,3]
]
You are not initializing your map. Since its inside initMap map function no one is calling it.
And there is no need to initialize every time when you got the data from the server. Just initialize once and use the same map object for your other works also.
And be careful while getting the data, You are trying to get the data in the index 5. But the array has only 0 to 4.
Try in the below fashion.
$(document).ready(function() {
function makeRequest() {
$.ajax({
url : "url",
type : "POST",
}).done(function(result) {
if (result) {
console.log("You Got your data", result);
}
});
};
var map = new google.maps.Map(document.getElementById('map'), {
zoom : 12,
center : new google.maps.LatLng('30.7333', '76.7794'),
mapTypeControlOptions : {
mapTypeIds : [ 'roadmap' ]
}
});
setInterval(makeRequest, (10 * 1000));
});
Here you will get data after 10 second. If you want at the first time itself means call makeRequest after initialization of map once.

GoogleMaps v3 API Create only 1 marker on rightclick

I am working on a new project and I am new to the Google maps API.
I need your help to mark only one marker on the map. Our clients would indicate their location with a right click and only if they remove the existing marker they reinsert their location.
I have tried if and else and the only result is that the map does not load.
I have created a fiddle with the code hope it helps: http://jsfiddle.net/JG9bG/
$(document).ready(function () {
var mapCenter = new google.maps.LatLng(39.39987199999999, -8.224454000000037); //Google map Coordinates
var map;
map_initialize(); // initialize google map
//############### Google Map Initialize ##############
function map_initialize() {
var googleMapOptions = {
center: mapCenter, // map center
zoom: 7, //zoom level, 0 = earth view to higher value
maxZoom: 18,
minZoom: 7,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.SMALL //zoom control size
},
scaleControl: true, // enable scale control
mapTypeId: google.maps.MapTypeId.ROADMAP // google map type
};
map = new google.maps.Map(document.getElementById("google_map"), googleMapOptions);
//Load Markers from the XML File, Check (map_process.php)
$.get("map_process.php", function (data) {
$(data).find("marker").each(function () {
var name = $(this).attr('name');
var address = '<p>' + $(this).attr('address') + '</p>';
var type = $(this).attr('type');
var point = new google.maps.LatLng(parseFloat($(this).attr('lat')), parseFloat($(this).attr('lng')));
create_marker(point, name, address, false, false, false, "http://google.com/mapfiles/ms/micons/blue.png");
});
});
//Right Click to Drop a New Marker
myListener = google.maps.event.addListener(map, 'rightclick', function (event) {
//Edit form to be displayed with new marker
var EditForm = '<p><div class="marker-edit">' +
'<form action="ajax-save.php" method="POST" name="SaveMarker" id="SaveMarker">' +
'<label for="pid"><span> Property Id: </span><input type="text" readonly name="pid" class="save-propid" value="<?php echo $prop_id;?>" maxlength="40" /></label>' +
'<label for="pName"><span>Place Name :</span><input type="text" name="pName" class="save-name" placeholder="Enter Title" maxlength="40" /></label>' +
'<label for="pDesc"><span>Description :</span><textarea name="pDesc" class="save-desc" placeholder="Enter Address" maxlength="150"></textarea></label>' +
//'<label for="pType"><span>Type :</span> <select name="pType" class="save-type"><option value="Rent">Rent</option><option value="Sell">Sell</option><option value="Holiday Rentals">Holiday Rentals</option></select></label>'+
'</form>' +
'</div></p><button name="save-marker" class="save-marker">Save Marker Details</button>';
//Drop a new Marker with our Edit Form
create_marker(event.latLng, 'Insert your Property Location', EditForm, true, true, true, "http://google.com/mapfiles/ms/micons/green.png");
});
}
//############### Create Marker Function ##############
function create_marker(MapPos, MapTitle, MapDesc, InfoOpenDefault, DragAble, Removable, iconPath) {
//new marker
var marker = new google.maps.Marker({
position: MapPos,
map: map,
draggable: DragAble,
animation: google.maps.Animation.DROP,
title: "Hello World!",
icon: iconPath
});
//Content structure of info Window for the Markers
var contentString = $('<div class="marker-info-win">' +
'<div class="marker-inner-win"><span class="info-content">' +
'<h1 class="marker-heading">' + MapTitle + '</h1>' + MapDesc +
'</span><button name="remove-marker" class="remove-marker" title="Remove Marker">Remove Marker</button>' +
'</div></div>');
//Create an infoWindow
var infowindow = new google.maps.InfoWindow();
//set the content of infoWindow
infowindow.setContent(contentString[0]);
//Find remove button in infoWindow
var removeBtn = contentString.find('button.remove-marker')[0];
var saveBtn = contentString.find('button.save-marker')[0];
//add click listner to remove marker button
google.maps.event.addDomListener(removeBtn, "click", function (event) {
remove_marker(marker);
});
if (typeof saveBtn !== 'undefined') //continue only when save button is present
{
//add click listner to save marker button
google.maps.event.addDomListener(saveBtn, "click", function (event) {
var mReplace = contentString.find('span.info-content'); //html to be replaced after success
var mName = contentString.find('input.save-name')[0].value; //name input field value
var mDesc = contentString.find('textarea.save-desc')[0].value; //description input field value
//var mType = contentString.find('select.save-type')[0].value; //type of marker
var mpid = contentString.find('input.save-propid')[0].value; //prop id
if (mName == '' || mDesc == '') {
alert("Please enter Name and Description!");
} else {
save_marker(marker, mName, mDesc, /*mType, */ mpid, mReplace); //call save marker function
}
});
}
//add click listner to save marker button
google.maps.event.addListener(marker, 'click', function () {
infowindow.open(map, marker); // click on marker opens info window
});
if (InfoOpenDefault) //whether info window should be open by default
{
infowindow.open(map, marker);
}
}
//############### Remove Marker Function ##############
function remove_marker(Marker) {
/* determine whether marker is draggable
new markers are draggable and saved markers are fixed */
if (Marker.getDraggable()) {
Marker.setMap(null); //just remove new marker
} else {
//Remove saved marker from DB and map using jQuery Ajax
var mLatLang = Marker.getPosition().toUrlValue(); //get marker position
var myData = {
del: 'true',
latlang: mLatLang
}; //post variables
$.ajax({
type: "POST",
url: "http://.../.../.../cpanel.php?exe=client_properties/google/map_process",
data: myData,
success: function (data) {
Marker.setMap(null);
alert(data);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(thrownError); //throw any errors
}
});
}
}
//############### Save Marker Function ##############
function save_marker(Marker, mName, mAddress, /*mType, */ mpid, replaceWin) {
//Save new marker using jQuery Ajax
var mLatLang = Marker.getPosition().toUrlValue(); //get marker position
var myData = {
name: mName,
address: mAddress,
latlang: mLatLang,
/*type : mType, */
propid: mpid
}; //post variables
console.log(replaceWin);
$.ajax({
type: "POST",
url: "http://.../.../.../cpanel.php?exe=client_properties/google/map_process",
data: myData,
success: function (data) {
replaceWin.html(data); //replace info window with new html
Marker.setDraggable(false); //set marker to fixed
Marker.setIcon('http://google.com/mapfiles/ms/micons/blue.png'); //replace icon
},
error: function (xhr, ajaxOptions, thrownError) {
alert(thrownError); //throw any errors
}
});
}
});
Thanks for your help
Backend:
<?php
//PHP 5 +
// database settings
$db_username = '';
$db_password = '';
$db_name = '';
$db_host = 'localhost';
//mysqli
$mysqli = new mysqli($db_host, $db_username, $db_password, $db_name);
if (mysqli_connect_errno())
{
header('HTTP/1.1 500 Error: Could not connect to db!');
exit();
}
################ Save & delete markers #################
if($_POST) //run only if there's a post data
{
//make sure request is comming from Ajax
$xhr = $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest';
if (!$xhr){
header('HTTP/1.1 500 Error: Request must come from Ajax!');
exit();
}
// get marker position and split it for database
$mLatLang = explode(',',$_POST["latlang"]);
$mLat = filter_var($mLatLang[0], FILTER_VALIDATE_FLOAT);
$mLng = filter_var($mLatLang[1], FILTER_VALIDATE_FLOAT);
//Delete Marker
if(isset($_POST["del"]) && $_POST["del"]==true)
{
$results = $mysqli->query("DELETE FROM tblmarkers WHERE geo_lat=$mLat AND geo_lng=$mLng");
if (!$results) {
header('HTTP/1.1 500 Error: Could not delete Marker!');
exit();
}
exit("Done!");
}
$mName = filter_var($_POST["name"], FILTER_SANITIZE_STRING);
$mAddress = filter_var($_POST["address"], FILTER_SANITIZE_STRING);
/* $mType = filter_var($_POST["type"], FILTER_SANITIZE_STRING);*/
$mpid = filter_var($_POST["propid"], FILTER_SANITIZE_STRING);
$results = $mysqli->query("INSERT INTO tblmarkers (geo_name, geo_address, geo_lat, geo_lng, prop_id) VALUES ('$mName','$mAddress',$mLat, $mLng, '$mpid')");
/* $results = $mysqli->query("INSERT INTO tblmarkers (geo_name, geo_address, geo_lat, geo_lng, geo_type, prop_id) VALUES ('$mName','$mAddress',$mLat, $mLng, '$mType', '$mpid')");*/
if (!$results) {
header('HTTP/1.1 500 Error: Could not create marker!');
exit();
}
$output = '<h1 class="marker-heading">'.$mName.'</h1><p>'.$mAddress.'</p>';
exit($output);
}
################ Continue generating Map XML #################
//Create a new DOMDocument object
$dom = new DOMDocument("1.0");
$node = $dom->createElement("markers"); //Create new element node
$parnode = $dom->appendChild($node); //make the node show up
// Select all the rows in the markers table
$results = $mysqli->query("SELECT * FROM tblmarkers WHERE 1");
if (!$results) {
header('HTTP/1.1 500 Error: Could not get markers!');
exit();
}
//set document header to text/xml
header("Content-type: text/xml");
// Iterate through the rows, adding XML nodes for each
while($obj = $results->fetch_object())
{
$node = $dom->createElement("marker");
$newnode = $parnode->appendChild($node);
$newnode->setAttribute("geo_name",$obj->name);
$newnode->setAttribute("geo_address", $obj->address);
$newnode->setAttribute("geo_lat", $obj->lat);
$newnode->setAttribute("geo_lng", $obj->lng);
$newnode->setAttribute("geo_type", $obj->type);
}
echo $dom->saveXML();
Try this :
google.maps.event.addListener(map, "rightclick",function(event){
marker = new google.maps.Marker({
position: event.latLng,
title: 'Changer la position',
map: map,
draggable: true
});
this is an example : http://jsfiddle.net/hweb/M7K4L/
One option:
declare the marker globally (outside of any function definition):
var marker = null;
check to see if it exists, if it does delete it before creating one at the new location:
function create_marker(MapPos, MapTitle, MapDesc, InfoOpenDefault, DragAble, Removable, iconPath) {
if ((marker != null) && marker.setMap) {
marker.setMap(null);
marker = null;
}
//new marker
marker = new google.maps.Marker({
position: MapPos,
map: map,
draggable: DragAble,
animation: google.maps.Animation.DROP,
title: "Hello World!",
icon: iconPath
});
working fiddle

Categories