I want to display marker inside the polygon like this example that i followed.
Point in polygon
But the marker did not show up.I think there is missing in my code,this is the coordinates that i saved to my database.
53.198524,-105.762383
53.198566,-105.765083
53.199001,-105.762314
53.199394,-105.765083
53.199409,-105.765091
53.199421,-105.762123
53.199425,-105.763580
I appreciate someone can help me to figure it out on how to get this work.
var map;
var polySides = 7;
var polyLat = new Array();
polyLat[0]=53.198524;
polyLat[1]=53.198566;
polyLat[2]=53.199001;
polyLat[3]=53.199394;
polyLat[4]=53.199409;
polyLat[5]=53.199421;
polyLat[6]=53.199425;
polyLat[7]=53.198524;
var polyLng = new Array();
polyLng[0]=-105.762383;
polyLng[1]=-105.765083;
polyLng[2]=-105.762314;
polyLng[3]=-105.765083;
polyLng[4]=-105.765091;
polyLng[5]=-105.762123;
polyLng[6]=-105.763580;
polyLng[7]=-105.762383;
var maxLat = Math.max.apply(null,polyLat);
var minLat = Math.min.apply(null,polyLat);
var maxLng = Math.max.apply(null,polyLng);
var minLng = Math.min.apply(null,polyLng);
var bounds = new google.maps.LatLngBounds;
function initialize() {
initial = new google.maps.LatLng(53.199246241276875,-105.76864242553711);
var mapOptions = {
zoom: 16,
center: initial,
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.LARGE
},
mapTypeControl: false
};
map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
}
$(function () {
$.ajax({
type:'post',
dataType:'json',
data:'maxLat='+maxLat +'&minLat='+minLat +'&maxLng='+maxLng +'&minLng='+minLng,
url:'polygeofence.php',
success: function(data){
bounds = new google.maps.LatLngBounds();
$.each(data,function(i,dat){
if (pointInPolygon(polySides,polyLat,polyLng,dat.lat,dat.lng)){
var latlng = new google.maps.LatLng(parseFloat(dat.lat),parseFloat(dat.lng));
addMarker(latlng);
bounds.extend(latlng);
}
});
map.fitBounds(bounds);
}
});
});
function pointInPolygon(polySides,polyX,polyY,x,y) {
var j = polySides-1 ;
oddNodes = 0;
for (i=0; i<polySides; i++) {
if (polyY[i]<y && polyY[j]>=y || polyY[j]<y && polyY[i]>=y) {
if (polyX[i]+(y-polyY[i])/(polyY[j]-polyY[i])*(polyX[j]-polyX[i])<x) {
oddNodes=!oddNodes;
}
}
j=i;
}
return oddNodes;
}
function addMarker(latlng){
marker = new google.maps.Marker({
position: latlng,
map: map,
draggable: false
});
marker.setMap(map);
}
google.maps.event.addDomListener(window, 'load', initialize);
php code
$minlat = $_POST['minLat'];
$maxlat = $_POST['maxLat'];
$minlng = $_POST['minLng'];
$maxlng = $_POST['maxLng'];
$queryresult = mysql_query("SELECT * FROM geofencetbl WHERE
(lat>='$minlat' AND lat<='$maxlat')
AND (lng>='$minlng' AND lng<='$maxlng')
");
$results = array(
'lat' => array(),
'lng' => array(),
);
while($row=mysql_fetch_array($queryresult,MYSQL_BOTH)){
$results['lat'][] =$row['lat'];
$results['lng'][] =$row['lng'];
}
echo json_encode($results);
Edit:after edited my code,I have problem on my sucess dat.lat and dat.lng are undefined
Quite a lot of issues in your code. You are missing many variables declarations, and other stuff.
I commented most of my changes like that:
// missing bounds object here
var bounds = new google.maps.LatLngBounds();
I removed the AJAX part since of course it is not going to work. I am just creating one marker. No polygon. But at least this shows you that a correct LatLng object is passed to the addMarker() function.
Hope this helps!
JSFiddle demo
Edit:
Here is how you should create your JSON output.
$sql = "SELECT * FROM geofencetbl WHERE (lat>='$minlat' AND lat<='$maxlat') AND (lng>='$minlng' AND lng<='$maxlng')";
$result = $db->query($sql) or die($db->error);
while ($obj = $result->fetch_object()) {
$results[] = $obj;
}
echo json_encode($results);
Then in your AJAX success function, log dat and you should understand how to deal with it!
Related
I am using google map api with contain location function .... i am retrieving latitude longitude from database i am using foreach loop to get result.If marker is within polygon it will stop foreach but problem it is not showing any result. Result come out is from last row query how can i fix it.It is showing me only last row from database .Below is my code
<?php
if(!empty($zone)){
foreach($zone as $findzone)
{
$exploded_data=explode('),',$findzone['zone_latlog']);
$count=count($exploded_data);
?>
<script>
var latitude = document.getElementById('latitude').value;
var longitude = document.getElementById('longitude').value;
var map;
var coord1 = new google.maps.LatLng(latitude, longitude);
function initialize() {
var map = new google.maps.Map(
document.getElementById("map_canvas"), {
center: new google.maps.LatLng(33.714760, 73.083160),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var bermudaTriangle = new google.maps.Polygon({
map: map,
paths: [
<?php
for($i=0;$i<$count;$i++){
echo "new google.maps.LatLng".$exploded_data[$i]."),";
}
?>
]
});
var bounds = new google.maps.LatLngBounds();
for (var i=0; i<bermudaTriangle.getPath().getLength(); i++) {
bounds.extend(bermudaTriangle.getPath().getAt(i));
}
bounds.extend(coord1);
var marker1 = new google.maps.Marker({
map: map,
position: coord1
});
map.setCenter(bounds.getCenter());
map.setZoom(11);
checkInPolygon(marker1, bermudaTriangle);
}
google.maps.event.addDomListener(window, "load", initialize);
function checkInPolygon(marker, polygon) {
var infowindow = new google.maps.InfoWindow();
var html = "";
if (google.maps.geometry.poly.containsLocation(marker.getPosition(), polygon)) {
html = "inside polygon";
} else {
html = "outside polygon";
}
infowindow.setContent(html);
infowindow.open(map, marker);
}
</script>
<?php
}}?>
How to fix that problem that show me only only that polygon that has my latitude longitude marker
I want to display multiple directions with dragable waypoints and save each waypoints.
On my project I can click on the map to create the routes, generating a wayA point and a wayB point and draw a route between them. So, I can make multiple routes.
I can also save them on the database.
The problem is load this points on the map again fetching them on the database and drawing all on the map.
I have two pages, on index.htm you can draw your routes and save them, and on loady.htm you can load them on the map.
I tried somethings but without sucess, I will post my try here.
This is my resumed index.htm
var map, ren, ser;
var data = {};
var wayA = [];
var wayB = [];
var directionResult = [];
function goma() <---Initialize
{
google.maps.event.addListener(map, "click", function(event) {
if (wayA.length == wayB.length) {
wayA.push(new google.maps.Marker({
draggable: true,
position: event.latLng,
map: map
}));
} else {
wayB.push(new google.maps.Marker({
draggable: true,
position: event.latLng,
map: map
}));
ren = new google.maps.DirectionsRenderer( {'draggable':true} );
ren.setMap(map);
ren.setPanel(document.getElementById("directionsPanel"));
ser = new google.maps.DirectionsService();
ser.route({ 'origin': wayA[wayA.length-1].getPosition(), 'destination': wayB[wayB.length-1].getPosition(), 'travelMode': google.maps.DirectionsTravelMode.DRIVING},function(res,sts) {
if(sts=='OK') {
directionResult.push(res);
ren.setDirections(res);
} else {
directionResult.push(null);
} })
} }); }
function save_waypoints()
{
var w=[],wp;
var rleg = ren.directions.routes[0].legs[0];
data.start = {'lat': rleg.start_location.lat(), 'lng':rleg.start_location.lng()}
data.end = {'lat': rleg.end_location.lat(), 'lng':rleg.end_location.lng()}
var wp = rleg.via_waypoints
for(var i=0;i<wp.length;i++)w[i] = [wp[i].lat(),wp[i].lng()]
data.waypoints = w;
var str = JSON.stringify(data)
var jax = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
jax.open('POST','process.php');
jax.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
jax.send('command=save&inventoresdegara='+str)
jax.onreadystatechange = function(){ if(jax.readyState==4) {
if(jax.responseText.indexOf('bien')+1)alert('Mapa Atualizado !');
else alert(jax.responseText)
}}
}
This is the resumed loady.htm with my try
var map, ren, ser;
var data = {};
var wayA = [];
var wayB = [];
var directionResult = [];
function goma() {
ren = new google.maps.DirectionsRenderer( {'draggable':true} );
ren.setMap(map);
ren.setPanel(document.getElementById("directionsPanel"));
ser = new google.maps.DirectionsService();
fetchdata();
function setroute(os)
{
var wp = [];
for(var i=0;i<os.waypoints.length;i++)
wp[i] = {'location': new google.maps.LatLng(os.waypoints[i][0], os.waypoints[i][3]),'stopover':false }
ser.route({ 'origin': wayA[wayA.length-1].setPosition(), 'destination': wayB[wayB.length-1].setPosition(), 'travelMode': google.maps.DirectionsTravelMode.DRIVING},function(res,sts) {
if(sts=='OK') {
directionResult.push(res);
ren.setDirections(res);
} else {
directionResult.push(null);
}
});
}
function fetchdata()
{
var jax = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
jax.open('POST','process.php');
jax.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
jax.send('command=fetch')
jax.onreadystatechange = function(){ if(jax.readyState==4) {
try { setroute( eval('(' + jax.responseText + ')') ); }
catch(e){ alert(e); }
}}
}
This is my php file:
<?
if($_REQUEST['command']=='save')
{
$query = "insert into inventoresdegara set value='$data'";
if(mysql_query($query))die('bien');
die(mysql_error());
}
if($_REQUEST['command']=='fetch')
{
//$query = "select value from inventoresdegara";
$query = "SELECT value FROM inventoresdegara";
if(!($res = mysql_query($query)));
$rs = mysql_fetch_array($res,1);
die($rs['value']);
}
?>
This is a image from my database to you know how the information are saved
The only thing that I need to do is load this values to the map, please help me =).
Thanks !
After my try, the loady.htm was this on ser.routes
ser.route({'origin':new google.maps.LatLng(os.start.lat,os.start.lng),
'destination':new google.maps.LatLng(os.end.lat,os.end.lng),
'waypoints': wp,
'travelMode': google.maps.DirectionsTravelMode.DRIVING},function(res,sts) {
if(sts=='OK')ren.setDirections(res);
}
If the reason to saving waypoints is to reproduce the route they came from, you're better off saving the entire route and then showing it on the map without re-requesting the route again. See Displaying results of google direction web service without using javascript api
Otherwise, if you just want to get a fresh route from A to B through waypoints, your current approach of calling ser.route() with them is correct.
I wonder whether someone may be able to help me please.
I using the code shown below to correctly plot markers retrieved from a MySQL database on a Google Map.
<script type="text/javascript">
//Sample code written by August Li
var icon = new google.maps.MarkerImage("images/location-marker-2.png")
new google.maps.Point(16, 32);
var center = null;
var map = null;
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
});
}
function initMap() {
map = new google.maps.Map(document.getElementById("gmaps-canvas"), {
center: new google.maps.LatLng(0, 0),
zoom: 6,
scrollwheel: true,
draggable: true,
mapTypeId: google.maps.MapTypeId.SATELLITE
});
<?php
include("admin/link.php");
include("admin/opendb.php");
$query = mysql_query("SELECT * FROM `detectinglocations` WHERE `locationid` = '$lid'");
while ($row = mysql_fetch_array($query)){
$locationname=$row['locationname'];
$osgb36lat=$row['osgb36lat'];
$osgb36lon=$row['osgb36lon'];
echo ("addMarker($osgb36lat, $osgb36lon,'<b>$locationname</b><br/>');\n");
}
mysql_close($connect);
?>
center = bounds.getCenter();
map.fitBounds(bounds);
}
</script>
What I'm now trying to do is add further functionality that allows users to also click on the map to plot new markers, in essence using the pre-existing marker from the database as a point to work from, performing a reverse geocode.
I've been researching this for a number of days now and I've tried to implement a whole host of tutorials, but I just can't seem to get both parts of the functionality working.
I do know that to enable a on-click event I need to incorporate something along the lines of:
google.maps.event.addListener(map, 'click', function(event) {
marker.setPosition(event.latLng)
geocode_lookup( 'latLng', event.latLng );
});
}
but I must admit I'm a little unsure about what else I need to incorporate.
I just wondered whether someone may be able to take a look at this please, and I'd be very grateful if someone could show me where I've gone wrong.
Many thanks and kind regards
I wrote a separate maps page with just click-to-reverse-geocode functionality
http://jsfiddle.net/ZDQeM/
The address details are confusing to work with, I think. The results are an array, at different levels of precision, one might include the county, another the state, another the street address. Generally I only use results[0]. The details are in the docs: https://developers.google.com/maps/documentation/javascript/geocoding#GeocodingResponses
If you need specific information the sure way to obtain it is iterate through the whole results array until you find what you need (types[] containing postal_code, for example).
google.maps.event.addListener(map, 'click', function(event) {
userMarker = new google.maps.Marker({
map: map,
position: event.latLng
});
geocoder.geocode({'latLng': event.latLng}, function(results, status) {
if(status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
alert(results[0].formatted_address);
}
else {
alert("No results");
}
}
else {
alert("Geocoding unsuccessful: Status " + status);
}
});
});
Where in your code?
<script type="text/javascript">
//Sample code written by August Li
var icon = new google.maps.MarkerImage("images/location-marker-2.png")
new google.maps.Point(16, 32);
var center = null;
var map = null;
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
});
}
function initMap() {
map = new google.maps.Map(document.getElementById("gmaps-canvas"), {
center: new google.maps.LatLng(0, 0),
zoom: 6,
scrollwheel: true,
draggable: true,
mapTypeId: google.maps.MapTypeId.SATELLITE
});
<?php
include("admin/link.php");
include("admin/opendb.php");
$query = mysql_query("SELECT * FROM `detectinglocations` WHERE `locationid` = '$lid'");
while ($row = mysql_fetch_array($query)){
$locationname=$row['locationname'];
$osgb36lat=$row['osgb36lat'];
$osgb36lon=$row['osgb36lon'];
echo ("addMarker($osgb36lat, $osgb36lon,'<b>$locationname</b><br/>');\n");
}
mysql_close($connect);
?>
center = bounds.getCenter();
map.fitBounds(bounds);
var geocoder = new google.maps.Geocoder();
google.maps.event.addListener(map, 'click', function(event) {
var userMarker = new google.maps.Marker({
map: map,
position: event.latLng
});
geocoder.geocode({'latLng': event.latLng}, function(results, status) {
if(status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
alert(results[0].formatted_address);
}
else {
alert("No results");
}
}
else {
alert("Geocoding unsuccessful: Status " + status);
}
});
});
}
</script>
Im setting some json using wordpress post data on a page and then passing that json to some JS which loops through and adds markers to a map. I'm so close to getting it working, just need to figure out this last part.
My PHP code to create the json from an array:
<script type="text/javascript">
var markers = <?php echo json_encode($pageposts);?>
</script>
Here is my JS code:
var infowindow = null;
$(document).ready(function(){
initialize();
});
function initialize() {
var centerMap = new google.maps.LatLng(41.141208, -73.263726);
var options = {
zoom: 12,
center: centerMap,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById('map'), options);
setMarkers(map, markers);
infowindow = new google.maps.InfoWindow({
content: "loading..."
});
}
function setMarkers(map, markers) {
for (var i = 0; i < markers.length; i++) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(markers[i].meta_value),
map: map
});
var contentString = "Some content";
google.maps.event.addListener(marker, "click", function () {
//infowindow.setContent(this.html);
//infowindow.open(map, this);
});
}
}
If you want to see the page, with the json embedded - check out this link:
http://www.fairfieldctguide.com/test-map
view-source:http://www.fairfieldctguide.com/test-map
Any help would be greatly appreciated!
Jake
google.maps.LatLng expects two numbers as an argument. Currently you are passing in a string which will result in an error. So you need to convert your markers[i].metavalue to two numbers like so:
function setMarkers(map, markers) {
for (var i = 0; i < markers.length; i++) {
latlng = markers[i].meta_value.split(",")
lat = parseFloat(latlng[0])
lng= parseFloat(latlng[1])
var marker = new google.maps.Marker({
position: new google.maps.LatLng(lat, lng),
map: map
});
var contentString = "Some content";
google.maps.event.addListener(marker, "click", function () {
//infowindow.setContent(this.html);
//infowindow.open(map, this);
});
}
}
If you don't want to do a converson you could just store lat and lng values as numbers in separate properties. So your json would look like this:
var markers = [{
"ID":"883",
"post_title":"Tucker's Cafe",
"meta_key":"meta_geo",
"lat":41.1674377,
"lng": -73.2236554
}
and you would add a marker like so:
var marker = new google.maps.Marker({
position: new google.maps.LatLng(markers[i].lat, markers[i].lng),
map: map
});
I'm trying to display an array of postcodes onto a google map using PHP and using the Symfony Framework (1.0)
The main problem I am having, is that there is some text associated with each marker, i.e when you click the marker a popup appears.
The main problem is that the text should point to the correct postcode/marker on the map, but for some reason this doesn't seem to be the case:
<?php
$addresses = array();
foreach($contents->getResults() as $content):
$addresses[] = array(
'postcode'=>sprintf('%s',str_replace(' ','',$content->getPostalCode())),
'html'=>escape_javascript(get_partial('property/propertyList',array('content'=>$content))),
);
endforeach;
?>
<?php
echo javascript_tag("
var map;
var localSearch = new GlocalSearch();
var center = false;
var icon = new GIcon();
icon.image = 'http://www.google.com/mapfiles/marker.png';
icon.shadow = 'http://www.google.com/mapfiles/shadow50.png';
icon.iconSize = new GSize(20, 34);
icon.shadowSize = new GSize(37, 34);
icon.iconAnchor = new GPoint(10, 34);
var delay = 100;
var bounds = new GLatLngBounds();
var addresses = ".json_encode($addresses).";
var nextAddress = 0;
function theNext() {
if (nextAddress < addresses.length) {
var postcode = addresses[nextAddress].postcode;;
var html = addresses[nextAddress].html
setTimeout('getAddress(\"'+postcode+'\",\"'+html+'\",theNext)', delay);
nextAddress++;
}
}
function getAddress(search, html, next) {
usePointFromPostcode(search, html);
next();
}
var geoCount = 0;
function usePointFromPostcode(address, html, callbackFunction) {
localSearch.setSearchCompleteCallback(null,
function() {
if (localSearch.results[0])
{
geoCount++;
var resultLat = localSearch.results[0].lat;
var resultLng = localSearch.results[0].lng;
var point = new GLatLng(resultLat,resultLng);
var marker = new GMarker(point);
GEvent.addListener(marker, 'click', function() {
marker.openInfoWindowHtml(html);
});
map.addOverlay(marker);
bounds.extend(point);
if(geoCount == addresses.length) {
setCenterToBounds();
}
}else{
//console.info('Postcode not found!', address);
}
});
localSearch.execute(address + ', UK');
}
function placeMarkerAtPoint(point, html)
{
var marker = new GMarker(point,icon);
map.addOverlay(marker);
}
function setCenterToBounds()
{
map.setCenter(bounds.getCenter());
map.setZoom(map.getBoundsZoomLevel(bounds));
console.info('zoom',map.getBoundsZoomLevel(bounds));
}
function mapLoad() {
if (GBrowserIsCompatible()) {
map = new GMap2(document.getElementById('map'));
map.addControl(new GLargeMapControl());
map.addControl(new GMapTypeControl());
theNext();
}
}
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
oldonload();
func();
}
}
}
function addUnLoadEvent(func) {
var oldonunload = window.onunload;
if (typeof window.onunload != 'function') {
window.onunload = func;
} else {
window.onunload = function() {
oldonunload();
func();
}
}
}
addLoadEvent(mapLoad);
addUnLoadEvent(GUnload);
")
?>
It only happens on some of the markers though. It is like it finds the postcode, puts the marker on, but then displays the wrong details for it
Ok, so it seems that the data coming back from Google, seemed to come back in the wrong order.
Changing the var delay = 100 to var delay = 200 seemed to fix this
Even though it made the map load a little bit slower