parse xml with php , google maps api v3 markers - javascript

I'm trying to find a way to use the function initialize inside a php file.i parse the xml file with the file_get_contents
$xml = file_get_contents('http://www.123.org/upload/123.xml');
include 'xml_regex.php';
$news_items = element_set('item', $xml);
foreach($news_items as $item) {
$description = value_in('description', $item);
$glat = value_in( 'glat', $item );
$glon = value_in( 'glon', $item );
$item_array[] = array(
'description' => $description,
'glat'=>$glat,
'glon'=>$glon
);
}
the function initialize
</script>
function initialize() {
var mapOptions = {
zoom: 6,
center: new google.maps.LatLng( 38.822590,24.653320 )
};
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);
<?php foreach ( $item_array as $item ) {
//how can i use this lines inside the loop?
//var latlng = new google.maps.LatLng(parseFloat("<?php $glat ?>"),
//parseFloat("<?php $glon ?>"));
//alert (latlng);
//also inside the loop i wanna use the createMarker funciton
}?>
</script>
Any ideas?

Finally i found the way!Just quote the code.Maybe it will help someone in the future!
<?php foreach ( $item_array as $item ) : ?>
var latlng = new google.maps.LatLng(parseFloat(<?php echo $item['glat']; ?>),
parseFloat(<?php echo $item['glon']; ?>));
if ( '<?php echo $item["temp"]; ?>' <= "1 °C" ) {
var marker = createMarker( latlng,cold );
}
function createMarker( latlng,cold ) {
var marker = new google.maps.Marker({
position: latlng,
map: map,
icon: cold
});
return marker;
}

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.

Trying to get markers dynamically from database using php and javascript

I am trying to get markers dynamically from the database using sql and php. The problem that i am facing is making the marker array in javascript. I have already referred the questions asked on stackoverflow but no luck...
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
alert("Geolocation is not supported by this browser.");
}
}
function showPosition(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
initMap(latitude,longitude);
addMarker(latitude,longitude);
}
function initMap(latitude,longitude){
var options = {center :{lat:latitude, lng :longitude} ,
zoom:8
}
var map = new google.maps.Map(document.getElementById('map'),options);
var marker = new google.maps.Marker({
position:{lat:latitude, lng :longitude},
map:map
})
}
var markers = [
<?php
require_once '../includes/dbconfig.inc.php';
$marker_fetcher = "SELECT ad_lat,ad_long FROM `tbl_ads`";
$result = mysqli_query($conn,$marker_fetcher);
while ($row = mysqli_fetch_assoc($result)) {
$lat = $row['ad_lat'];
$long = $row['ad_long'];
echo '{';
echo $lat;
echo ',';
echo $long;
echo '},';
}
?>
];
function addMarker(props){
alert(markers.length)
}
$(document).ready(function(){
getLocation();
});
javascript from source
{19.1643153,72.98971789999996},{19.1816553,72.9711542},{19.2403305,73.13053949999994},{29.6856929,76.99048249999998},{19.2532887,73.13668610000002},{19.2532887,73.13668610000002},{19.2292364,72.85967119999998},{19.2292364,72.85967119999998},{19.0606917,72.83624970000005},{18.5596581,73.7799374},{19.157935,72.99347620000003},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{19.2403305,73.13053949999994},{19.157935,72.99347620000003},{19.157935,72.99347620000003},{19.157935,72.99347620000003},{19.157935,72.99347620000003},{53.9332706,-116.5765035},{19.157935,72.99347620000003},{19.2183307,72.97808970000006},{19.157935,72.99347620000003},{53.9332706,-116.5765035},{46.227638,2.213749000000007},{19.157935,72.99347620000003},{19.157935,72.99347620000003},
The array of marker positions is not a valid javascript array. Make the positions to be google.maps.LatLngLiteral objects. Change the code that generates the javascript for your markers array from:
var markers = [
<?php
require_once '../includes/dbconfig.inc.php';
$marker_fetcher = "SELECT ad_lat,ad_long FROM `tbl_ads`";
$result = mysqli_query($conn,$marker_fetcher);
while ($row = mysqli_fetch_assoc($result)) {
$lat = $row['ad_lat'];
$long = $row['ad_long'];
echo '{';
echo $lat;
echo ',';
echo $long;
echo '},';
}
?>
];
To:
var markers = [
<?php
require_once '../includes/dbconfig.inc.php';
$marker_fetcher = "SELECT ad_lat,ad_long FROM `tbl_ads`";
$result = mysqli_query($conn,$marker_fetcher);
while ($row = mysqli_fetch_assoc($result)) {
$lat = $row['ad_lat'];
$long = $row['ad_long'];
echo '{lat:';
echo $lat;
echo ', lng:';
echo $long;
echo '},';
}
?>
];
So your markers array looks like this:
var markers = [
{lat: 19.1643153, lng: 72.98971789999996},
{lat: 19.1816553, lng: 72.9711542},
{lat: 19.2403305, lng: 73.13053949999994},
// ...
];
proof of concept fiddle
code snippet:
var bounds;
var map = null;
function initMap(latitude, longitude) {
var options = {
center: {
lat: latitude,
lng: longitude
},
zoom: 8
}
map = new google.maps.Map(document.getElementById('map'), options);
var marker = new google.maps.Marker({
position: {
lat: latitude,
lng: longitude
},
map: map
})
bounds = new google.maps.LatLngBounds();
for (var i = 0; i < markers.length; i++) {
addMarker(markers[i]);
}
map.fitBounds(bounds);
}
var markers = [{lat:19.1643153, lng:72.98971789999996}, {lat:19.1816553, lng:72.9711542}, {lat:19.2403305, lng:73.13053949999994}, {lat:29.6856929, lng:76.99048249999998}, {lat:19.2532887, lng:73.13668610000002}, {lat:19.2532887, lng:73.13668610000002}, {lat:19.2292364, lng:72.85967119999998}, {lat:19.2292364, lng:72.85967119999998}, {lat:19.0606917, lng:72.83624970000005}, {lat:18.5596581, lng:73.7799374}, {lat:19.157935, lng:72.99347620000003}, {lat:30.900965, lng:75.85727580000002}, {lat:19.2403305, lng:73.13053949999994}, {lat:19.157935, lng:72.99347620000003}, {lat:53.9332706, lng:-116.5765035}, {lat:19.157935, lng:72.99347620000003}, {lat:19.2183307, lng:72.97808970000006}, {lat:46.227638, lng:2.213749000000007}];
function addMarker(props) {
console.log(JSON.stringify(props));
var marker = new google.maps.Marker({
position: props,
map: map
});
console.log(marker.getPosition().toUrlValue(6));
bounds.extend(marker.getPosition());
}
google.maps.event.addDomListener(window, "load", function() {
initMap(19.16, 75.857)
});
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map"></div>

google maps show multiple location (Error: locations[i] is undefined)

I am trying to show multiple users location using Google Map API, I have to show all value from master_service_provider table for this I am using while loop.
But I am getting JavaScript error Type Error: locations[i] is undefined.
<div id="map"></div>
<script>
var map;
function initMap() {
var i = '0';
<?php
$result=$conn->query("SELECT * FROM `master_service_provider`");
$a=0;
while($row = mysqli_fetch_array($result)) {
$service_provider_id = $row['id'];
$fullname = $row['fullname'];
$fulladdress = $row['fulladdress'];
$phone = $row['phone'];
$lat = $row['lat'];
$lng = $row['lng'];
?>
var <?php echo 's'.$phone; ?> = {
info: '<h3><?php echo $fullname; ?></h3>\
<h4><?php echo $fulladdress; ?></h4>\
View Info',
lat: <?php echo $lat; ?>,
long: <?php echo $lng; ?>
};
var locations = [
[<?php echo 's'.$phone; ?>.info, <?php echo 's'.$phone; ?>.lat, <?php echo 's'.$phone; ?>.long, <?php echo $a++; ?>],
];
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map
});
google.maps.event.addListener(marker, 'click', (function (marker, i) {
return function () {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
i++;
<?php } ?>
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 11,
center: new google.maps.LatLng(19.198313, 72.893533),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow({});
var marker;
}
</script>
It should be something like this, I think.
Fill the ... parts yourself, but keep the general structure of the code.
Let me know if you get it to work
<?php
...
// do this on top, not in the middle of javascript
$result = $conn->query("SELECT id, lat, lng, fullname, fulladdress, phone FROM master_service_provider"); // don't use *, specify the columns you want
$mydata = array();
while($row = mysqli_fetch_assoc($result)) { // use _assoc rather than _array
$mydata[] = $row ; // push current row to the data object
}
// now we translate this php array to a javascript array of objects.
// it should resemble something like:
// var locations = [ {"id": "1", "lat":"4.51", "lng":"50.53", "fullname":"John Smith", ... }, {"id": "2", lat":"5.14", ...} ] ;
// use json_encode() to realize this
echo '<script>var locations = '. json_encode($mydata) .' ;</script>';
?>
<script>
var map;
function initMap() {
...
for(var i=0; i<locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i]['lat'], locations[i]['lng']),
title: locations[i]['fullname'],
map: map
});
...
google.maps.event.addListener(marker, 'click', (function (marker, i) {
return function () {
infowindow.setContent('phone: ' + locations[i]['phone']);
infowindow.open(map, marker);
}
})(marker, i));
}
...
}
</script>

Google Maps API marker based on data

So i have a set of data in my database, the data consist of location id (loc_id), longitude, and latitude. what i want to do is to create a map that consist of marker from all of my location data. what should i do first to create this map? because this is my first time using javascript.
currently the code that i used to show the map :
<script src="http://maps.googleapis.com/maps/api/js"></script>
<script>
function initialize() {
var mapProp = {
center:new google.maps.LatLng(-7.803164,110.3398252), zoom:10, mapTypeId:google.maps.MapTypeId.ROADMAP
};
var map=new google.maps.Map(document.getElementById("googleMap"),mapProp);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
You need to output the data in your database into javascript and then loop through them then add them to your map.
First get the data from your database and make it into a javascript array. FYI my PHP is very rusty
var locations = [
<?php
$query = 'SELECT * FROM sometable';
$result = mysql_query($query);
$currentrow = 0;
while ($row = mysql_fetch_assoc($result)) {
$currentrow++;
echo '{';
echo 'latitude : ' . $row[0] . ',';
echo 'longitude: ' . $row[1] ;
echo '}'.if(currentrow != msqli->num_rows){,}
}
?>
]
Then on the javascript you need to loop through the locations array and create them as markers.
for(var i = 0; i < locations.lengtht; i++){
var myLatLng = {
lat: locations[i].latitude,
lng: locations[i].longitude
};
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: 'Your title'
});
}

Pass resultset value to a javascript function

I have one resultset,
How can i pass its value to a javascript function ,and move internal pointer to next row.
<?php
$q=mysql_query("select * from tbl_map")or die(mysql_error());
$i=0;
?>
<script>
$(document).ready(function() {
// Initialize the Google Maps API v3
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var marker = null;
function autoUpdate() {
<?php
mysql_data_seek($q,$i);
$row=mysql_fetch_assoc($q);
$i++;
?>
lat=<?php echo $row['latitude']; ?>;
long=<?php echo $row['longitude']; ?>;
navigator.geolocation.getCurrentPosition(function(position) {
var newPoint = new google.maps.LatLng(lat,
long);
if (marker) {
// Marker already created - Move it
marker.setPosition(newPoint);
}
else {
// Marker does not exist - Create it
marker = new google.maps.Marker({
position: newPoint,
map: map
});
}
// Center the map on the new position
map.setCenter(newPoint);
});
// Call the autoUpdate() function every 5 seconds
setTimeout(autoUpdate, 5000);
}
autoUpdate();
});
</script>
I want to fetch latitude and longitude from database and pass to autoupdate()
but i can not move internal pointer ahead.
How to fix ?
Try this: in this method array of latitude and longitude is assigned to a javascript variable json in form of json data.
<script>
// ---- PHP Starts here which fetch data and is placed immediately after <script> tag open
// ---- and store to a variable in json format.
<?php
$q = mysql_query("select * from tbl_map")or die(mysql_error());
$response = array();
for($i = 0; $i < mysql_num_rows($q) ; $i++ )
{
mysql_data_seek($q, $i);
$row = mysql_fetch_assoc($q);
array_push( $response, array(
'lat'=>$row['latitude'],
'long'=>$row['longitude']
));
// ------ Here php assigns the array of data to `json`
// ------ `var json` is under scope of javascript
echo 'var json = ' . json_encode($response) . ';';
}
?>
// ---- PHP part ends here and javascript start
// ---- Testing the `json` var
console.log(json);
console.log(json.length);
$(document).ready(function() {
// Initialize the Google Maps API v3
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var c = 0;
var marker = null;
function autoUpdate() {
console.log(json[c].lat);
console.log(json[c].long);
navigator.geolocation.getCurrentPosition( function(position)
{
var newPoint = new google.maps.LatLng( json[c].lat, json[c].long );
if (marker) {
// Marker already created - Move it
marker.setPosition(newPoint);
}
else {
// Marker does not exist - Create it
marker = new google.maps.Marker({
position: newPoint,
map: map
});
}
// Center the map on the new position
map.setCenter(newPoint);
});
if (c == (json.length - 1)) { c = 0; } else { c++; }
// Call the autoUpdate() function every 5 seconds
setTimeout(autoUpdate, 5000);
}
autoUpdate();
});
</script>

Categories