Adding place markers to Google Map - php

I have this code below which draws a line on a google maps from co-ordinates from an XML file.
However I want it to show the first co-ordinate and the last coordinate with a place marker as well. I managed to do this without drawing the line by following the steps here:
https://developers.google.com/maps/articles/phpsqlajax_v3?csw=1
but can't seem to be able to integrate the 2. i.e Draw the line and have place markers at the start and finish.
I'm sure its just a tiny bit of code I have to add too the code I already have below but I'm wrecking my train trying to work it out. Any help would be greatly appreciated.
<!DOCTYPE html >
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>PHP/MySQL & Google Maps Example</title>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
//<![CDATA[
var customIcons = {
restaurant: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_blue.png'
},
bar: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_red.png'
}
};
function load() {
var point;
var flightPlanCoordinates=new Array();
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(50.431, -3.202),
zoom: 9,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR
},
navigationControl: true,
navigationControlOptions: {
style: google.maps.NavigationControlStyle.SMALL
}
});
downloadUrl("phpsqlajax_genxml.php", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
flightPlanCoordinates[i]=point;
}
var flightPath = new google.maps.Polyline({
path: flightPlanCoordinates,
strokeColor: "#FF0000",
strokeOpacity: 1.0,
strokeWeight: 2
});
flightPath.setMap(map);
});
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}
//]]>
</script>
</head>
<body onload="load()">
<div id="map" style="width: 500px; height: 300px"></div>
</body>
</html>

In the code that you posted above, you are never adding your markers to the map, which is done with the following code:
var marker = new google.maps.Marker({
map: map, //The Map Object
position: point //The location of the Marker
});
You would want to put this statement into your for loop as you iterate through the GPS points, and if it is the first iteration or the last iteration through the loop, than add your marker. You can than draw your polyline after the loop like you are doing in your posted example.

Related

Load markers from mysql database and display as markers on Google maps

I am using phonegap and I have a google map which locates the user and places a marker on the map. What I want to do is load markers from a mysql database which holds lat and long details for each place. Do I have to do this through php and ajax? This is the code I have at the moment. Thanks
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>Test</title>
<link rel="stylesheet" href="/master.css" type="text/css" media="screen" />
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" charset="utf-8" src="phonegap.js"></script>
<script type="text/javascript">
function onLoad() {
document.addEventListener("deviceready", onDeviceReady, false);
}
function onDeviceReady() {
navigator.geolocation.getCurrentPosition(onSuccess, onError,{'enableHighAccuracy':false,'timeout':10000});
}
//GEOLOCATION
var onSuccess = function(position) {
var myLat = position.coords.latitude;
var myLong = position.coords.longitude;
var myLatlng = new google.maps.LatLng(myLat, myLong);
//MAP
var mapOptions = {
center: new google.maps.LatLng(myLat, myLong),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"),
mapOptions);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title:"Hello World!"
});
};
// onError Callback receives a PositionError object
//
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
</script>
</head>
<body onload="onLoad()">
<div id="map_canvas" style="width:100%; height:100%"></div>
</body>
</html>
Define map
var map;
Initialize map:
function initialize(lat,lng, n) { //BY PASSING LATITUDE (lat), LONGITUDE (lng) AND THE TEXT (n) WILL SET A DEFAULT MARKER
var mapOptions = {
scaleControl: true,
center: new google.maps.LatLng(lat, lng),
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
var marker = new google.maps.Marker({
map: map,
position: map.getCenter()
});
var infowindow = new google.maps.InfoWindow();
infowindow.setContent('<b>ا'+n+'</b>');
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map, marker);
});
}
call this function in device ready function.
You can pass current lat, long-
var myLat = position.coords.latitude;
var myLong = position.coords.longitude;
call a ajax request and get location data from server.
Insert all latitude and longitude in locations array within your ajax success request and call setMarkers method
var loc_array = new Array(); //LOCATION ARRAY
$.each(server_response_array, function(i,v){
loc_array[i] = [v.lat, v.lng, v.temp_txt];
}
setMarkers(loc_array);
function setMarkers(locations){
//clearMap();
map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
var marker, i
for (i = 0; i < locations.length; i++)
{
var loan = locations[i]['txt'];
var lat = locations[i]['lat'];
var lng = locations[i]['lng'];
latlngset = new google.maps.LatLng(lat, lng);
var marker = new google.maps.Marker({
map: map, title: loan , position: latlngset, icon: 'http://maps.google.com/mapfiles/ms/icons/blue-dot.png' //THIS WILL SET A BLUE COLOR MARKER YOU CAN SET MORE COLOR AND ALSO CAN MANAGE FROM DATABASE
});
//map.setCenter(marker.getPosition())
var content = loan;
var infowindow = new google.maps.InfoWindow()
google.maps.event.addListener(marker,'click', (function(marker,content,infowindow){
return function() {
infowindow.setContent(content);
infowindow.open(map,marker);
};
})(marker,content,infowindow));
}
}
Also see this link
goole-map-javascript-api-unable-to-load-markers-from-mysql-database

Marking route on Google map with multiple latitude and longitude values from database

I have written a PHP and javaScript code which will retrieve latitude and longitude informations from Database and place markers on Google map according in appropriate places(using lat and lon values). This works fine.
I need to join these markers and draw route on the map. How to do it.
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<style type="text/css">
body { font: normal 10pt Helvetica, Arial; }
#map { width: 350px; height: 300px; border: 0px; padding: 0px; }
</style>
<script src="http://maps.google.com/maps/api/js?v=3&sensor=false" type="text/javascript"></script>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
var icon = new google.maps.MarkerImage("http://maps.google.com/mapfiles/ms/micons/blue.png",
new google.maps.Size(32, 32), new google.maps.Point(0, 0),
new google.maps.Point(16, 32));
var center = null;
var map = null;
var currentPopup;
var bounds = new google.maps.LatLngBounds();
function addMarker(lat, lng, info)
{
var pt = new google.maps.LatLng(lat, lng);
bounds.extend(pt);
var marker = new google.maps.Marker(
{
position: pt,
icon: icon,
map: map
});
var popup = new google.maps.InfoWindow(
{
content: info,
maxWidth: 300
});
google.maps.event.addListener(marker, "click", function()
{
if (currentPopup != null)
{
currentPopup.close();
currentPopup = null;
}
popup.open(map, marker);
currentPopup = popup;
});
google.maps.event.addListener(popup, "closeclick", function()
{
map.panTo(center);
currentPopup = null;
});
}
function initMap()
{
map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(0, 0),
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false,
mapTypeControlOptions:
{
style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR
},
navigationControl: true,
navigationControlOptions:
{
style: google.maps.NavigationControlStyle.SMALL
}
});
$.getJSON('googlescript.php', function(items)
{
for (var i = 0; i < items.length; i++) {
(function(item) {
addMarker(item.lat, item.long, '<b>' + item.name + '</b><br />' + item.desc);
})(items[i]);
}
});
center = bounds.getCenter();
map.fitBounds(bounds);
}
</script>
</head>
<body onload="initMap()" style="margin:0px; border:0px; padding:0px;">
<div id="map"></div>
</html>
Modify your JSON return function to something like this:
$.getJSON('googlescript.php', function(items)
{
var routePoints = [];
for (var i = 0; i < items.length; i++) {
(function(item) {
addMarker(item.lat, item.long, '<b>' + item.name + '</b><br />' + item.desc);
})(items[i]);
routePoints.push(new google.maps.LatLng(items[i].lat,items[i].long));
}
var route= new google.maps.Polyline({
path: routePoints,
strokeColor: "#FF0000",
strokeOpacity: 1.0,
strokeWeight: 2
});
route.setMap(map);
});
I think you look for the Polyline object and you can see how to use within the google maps documentation
If you got a larger project I can advice using gmap2 using .kml files. But you should be able to accomplish your goal using the google documentation easily..
You will need to learn about the POLYLINE ARRAYS to accomplish connecting all the markers with a line. The documentation explains it very well.
However, the polyline arrays use javascript arrays, so if you are looking for fetching the lat lng values from a Database then you should look for some way to pass an array of the lat lng's fetched from database to the JavaScript function. There is already an article in the site that shows how to work Using PHP/MySQL with Google Maps . Look into the article and learn using polyline arrays and that should help you out.

Load Dynamic Google Markers From MySQL

I wonder whether someone could help me please.
I'm using the script below to dynamically load Google markers from a MySQL database and the script works fine.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Map My Finds - My Finds Per Location</title>
<link rel="stylesheet" href="myfindsperlocation.css" type="text/css" media="all" />
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&language=en"></script>
<script type="text/javascript">
function load() {
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(54.312195845815246,-4.45948481875007),
zoom:14,
mapTypeId: 'satellite'
});
var infoWindow = new google.maps.InfoWindow;
downloadUrl("loadmyfindsperlocation.php", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < markers.length; i++) {
var locationid = markers[i].getAttribute("locationid");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("findosgb36lat")),
parseFloat(markers[i].getAttribute("findosgb36lon")));
var marker = new google.maps.Marker({
map: map,
position: point
});
bounds.extend(point);
map.fitBounds(bounds);
bindInfoWindow(marker, map, infoWindow, html);
}
});
}
function bindInfoWindow(marker, map, infoWindow, html) {
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker, html);
});
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}
</script>
</head>
<body onLoad="load()">
<div id="map"></div>
</body>
</html>
You'll see it's a relatively simple form, which calls the data from an external PHP file which is shown in my script here: downloadUrl("loadmyfindsperlocation.php", function(data) {
What I'm now trying to do is incorporate the PHP script into the above, but I can't seem to get the map to load and I suspect it's something to do in calling the file as a URL.
Forgive me for asking, I'm relatively new to PHP an XML, but could someone perhaps tell me please how I could call this without loading it as an external URL.
Many thanks and kind regards
I don't have either your CSS or PHP so I can only guess. Do you see errors in your Javascript console?
What I did was add the following styles and the map loaded, even with the PHP missing and giving me errors.
html, body, #map { margin: 0; padding: 0; height: 100% }
About loading the PHP, it has to be served to return a meaningful XML. You can have a pre-written XML and load that too.

Googlemaps stop recentering when updating markers

I'm completely new to both javascript and the googlemaps api but have had some great help on here the past few days and progressed my website a lot (thanks!). Now, I have a new problem. What I want to do, is load a set of markers from a database to a map, and then allow the user to input values into a form to filter the markers (For example, putting minimum and maximum length fields).
Here's my code, I hope it's understandable:
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
//<![CDATA[
var icons = {
icon: 'http://labs.google.com/ridefinder/images/mm_20_blue.png',
shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
};
function load() {
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(51.5100, 0.0000),
zoom: 10,
mapTypeId: 'roadmap'
});
var infoWindow = new google.maps.InfoWindow;
//min and max ride lengths sent from form
var minlength = document.getElementById("minlength").value;
var maxlength = document.getElementById("maxlength").value;
// Change this depending on the name of your PHP file
downloadUrl("phpsqlajax_genxml.php", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var length = markers[i].getAttribute("length");
if (minlength < length && length < maxlength) {
var date = markers[i].getAttribute("date");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var html = "<b>Date: " + date + "</b> <br/>Length: " + length;
var icon = icons;
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon,
shadow: icon.shadow
});
bindInfoWindow(marker, map, infoWindow, html);
}
}
});
}
function bindInfoWindow(marker, map, infoWindow, html) {
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}
//]]>
</script>
</head>
<link rel="stylesheet" type="text/css" href="style.css" />
<body onload="load()">
<div id="container">
<div id="maincontent">
<form name="findride">
Min length: <input type="number" id="minlength">(miles)<br>
Max length: <input type="number" id="maxlength">(miles)<br>
<input type="button" value="Update" onClick="load()"/>
<div id="map"></div>
</div>
</div>
The problem I am having, is that the map does not display the points before the user fills in the field and updates (I tried to set some initial maxlength and minlength values, but that didnt work either). After the user enters this data, the points are displayed, but the map keeps re-centering - I would prefer it to stay in the same position and just have the markers change.
Well, maybe this is a bit out of my reach but if it can be done simply, I would really appreciate the help.
Changing your HTML to this :
Min length: <input type="number" id="minlength" value="5">(miles)<br>
Max length: <input type="number" id="maxlength" value="5">(miles)<br>
I have added value="5" to both inputs this means that when the script runs on load it should add some markers - you may need to change the number 5 to a more suitable value
Should fix the markers on startup issue.
And by default the map doesnt centre when adding a marker - see this simple example I add a marker at the centre point on load and then add another maker 3 seconds later - the map doesnt centre ....

How to know is marker inside polygon in google maps api

When You click on anywhere in map 1 new marker created and make polygon
its working fine but now my problem is i can't get is my marker which is coming from database is inside polygon or not, how to know it???
<?php include("config.php"); ?>
<?php $result = mysql_query("select * from `googlemaps`"); ?>
<html>
<head>
<title>Google Maps</title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var poly, map;
var markers = [];
var path = new google.maps.MVCArray;
function initialize() {
var LatLng = new google.maps.LatLng(23.183, 75.767);
map = new google.maps.Map(document.getElementById("map"), {
zoom: 12,
center: LatLng,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
function createMarker(point, title) {
var infowindow = new google.maps.InfoWindow({
content: "<span style='color:blue;'>"+title+"</span>"
});
var marker = new google.maps.Marker({
position: point,
map: map,
title:title
});
marker.Image ='https://d3szoh0f46td6t.cloudfront.net/public/1626980/small';
google.maps.event.addListener(marker, "click", function() {
infowindow.open(map,marker);
});
return marker;
}
<?php
if(mysql_num_rows($result)>0)
{
while( $data = mysql_fetch_array($result) )
{ ?>
createMarker(new google.maps.LatLng(<?php echo $data['lat']; ?>, <?php echo $data['lon']; ?>), "<?php echo $data['title']; ?>");
<?php }
}
?>
poly = new google.maps.Polygon({
strokeWeight: 3,
fillColor: '#5555FF'
});
poly.setMap(map);
poly.setPaths(new google.maps.MVCArray([path]));
google.maps.event.addListener(map, 'click', addPoint);
}
function addPoint(event) {
path.insertAt(path.length, event.latLng);
var marker = new google.maps.Marker({
position: event.latLng,
map: map,
draggable: true
});
markers.push(marker);
marker.setTitle("#" + path.length);
google.maps.event.addListener(marker, 'click', function() {
marker.setMap(null);
for (var i = 0, I = markers.length; i < I && markers[i] != marker; ++i);
markers.splice(i, 1);
path.removeAt(i);
}
);
google.maps.event.addListener(marker, 'dragend', function() {
for (var i = 0, I = markers.length; i < I && markers[i] != marker; ++i);
path.setAt(i, marker.getPosition());
document.getElementById("abc").innerHTML=path.setAt(i, marker.getPosition());
}
);
}
</script>
</head>
<body style="margin:0px; padding:0px;" onLoad="initialize()">
<div id="map" style="width:500px; height:500px;"></div>
<div id="abc"></div>
</body>
</html>
You might be asking how to check this javascript or php. I am not aware of a GIS framework in these areas.
Most of the spatial databases (like SQL Server/Postgresql which I have worked with) provide features like ST_Contains or ST_Distance which you can make use of. I think this is part of OpenGIS specification.
I think you might probably be using MYSQL. So may just need to search for a function.

Categories