how to use MySQL DB for EGmap extension in Yii - mysql

for example i have a MySQL database that contains latitude and longitude, how do I call these coordinates to be displayed in the map ? anyone can help me please?

Since your question and information are a bit unclear, these are my assumptions:
I assume that you have followed the instruction correctly to install the EGMap
extension into your yii application.
You want to place a marker at the said coordinates (latitude &
longitude).
Sample codes: (please adjust to fit your database tables and columns at the lines
commented as "// Get LatLong from table Location"). Place this straight into your view file example: protected/views/site/index.php
<!-- other html codes here -->
<div id="map-container">
<?php
// Get LatLong from table Location
$location=Location::model()->findByPk(1);
$latitude = $location->latitude;
$longitude = $location->longitude;
Yii::import('ext.gmap.*');
$gMap = new EGMap();
$gMap->setJsName('map');
$gMap->zoom = 10;
$mapTypeControlOptions = array(
'sensor'=>true,
'position'=> EGMapControlPosition::LEFT_BOTTOM,
'style'=>EGMap::MAPTYPECONTROL_STYLE_DROPDOWN_MENU
);
// Map settings
$gMap->mapTypeControlOptions= $mapTypeControlOptions;
$gMap->setWidth(800);
$gMap->setHeight(600);
$gMap->setCenter($latitude, $longitude);
// Prepare icon
$icon = new EGMapMarkerImage("http://google-maps-icons.googlecode.com/files/gazstation.png");
$icon->setSize(32, 37);
$icon->setAnchor(16, 16.5);
$icon->setOrigin(0, 0);
// Prepare marker
$marker = new EGMapMarker($latitude, $longitude, array('title' => 'Gas Station','icon'=>$icon));
$gMap->addMarker($marker);
$gMap->renderMap();
?>
</div>
<!-- other html codes here -->

Related

Calculate the distance between multi geolocations points

My application collects geolocation point from the user every certain amount of time, I am trying to use these points in order to calculate the distance from the first point through all of the points.
please note that when the user moves in a straight line, the geolocation points do not form a straight line, because the points I collect have a margin of error due to inaccuracy, thus I can't use something like Haversine formula because it will give incorrect value (longer distance than real distance)
and I can't use Google Maps Distance API because it calculates the distance between 2 points only, and it will be so expensive to call it 200 times to calculate distance through all points.
and I want to calculate this value on the server-side because of some security rules I have. so using the google maps SDK in the front end to calculate it is not an option either.
Any idea ...
One option would be to simplify the line, then run the data through the Google Roads API (assuming the travel is on roads), then measure the length of the resulting line (following the roads).
for anyone facing the same problem,I have followed this link
https://developers-dot-devsite-v2-prod.appspot.com/maps/documentation/roads/snap
here is my code in PHP
// snap the collected points from user to the nearest road using google API
$fields = array(
'path' => '60.170880,24.942795|60.170879,24.942796|60.170877,24.942796|60.170902,24.942654',
'key' => '<YOUR_KEY_HERE>'
);
$url = "https://roads.googleapis.com/v1/snapToRoads?" . http_build_query($fields, '', '&');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
$response = json_decode($response);
$totalDistance = 0;
$previousPoint = null;
foreach ($response->snappedPoints as $pointOnRoad) {
if(!$previousPoint){
$previousPoint = $pointOnRoad;
continue;
}
$totalDistance += getDistance($pointOnRoad->location->latitude, $pointOnRoad->location->longitude,
$previousPoint->location->latitude, $previousPoint->location->longitude);
}
echo $totalDistance;
// calculate distance between 2 geo points
function getDistance($latitude1, $longitude1, $latitude2, $longitude2) {
$earth_radius = 6371;
$dLat = deg2rad($latitude2 - $latitude1);
$dLon = deg2rad($longitude2 - $longitude1);
$a = sin($dLat/2) * sin($dLat/2) + cos(deg2rad($latitude1)) * cos(deg2rad($latitude2)) * sin($dLon/2) * sin($dLon/2);
$c = 2 * asin(sqrt($a));
$d = $earth_radius * $c;
return $d;
}
We are having similar kind of requirement. There are 2 paths and we need to make sure that each node in 1st path (except start and end) are at least 100 KM away from each other of 2nd path.
Can you please share code snippet or logic behind this.
Using Haversine formula in loop will impact performance. So, please suggest some better solution.

Google map as background to my sharpmap map not aligning correctly

I've been at this for quite a while now.
What I'm trying to achieve here is to add Google map as background layer to my Sharpmap, I'm able to achieve this but the problem I'm facing now is My map always centre's to a point near a Greenland sea in Google Map , it's like it won't take my centre point coordinates.
I'm using Sharpmap 1.1 with BruTile 0.7.4.4
So far I've done the below.
SharpMap.Map _map = new SharpMap.Map();
SharpMap.Layers.VectorLayer layer = new SharpMap.Layers.VectorLayer("parcel");
SharpMap.Data.Providers.MsSqlSpatial DBlayer = new SharpMap.Data.Providers.MsSqlSpatial(_connectionString, "XXXXXX", "XXXX", "XXX");
layer.Style.Fill = new SolidBrush(Color.Transparent);
layer.Style.Outline = new Pen(Color.Black);
layer.Style.EnableOutline = true;
layer.MaxVisible = 13000;
layer.DataSource = DBlayer;
ProjNet.CoordinateSystems.Transformations.CoordinateTransformationFactory ctFact = new ProjNet.CoordinateSystems.Transformations.CoordinateTransformationFactory();
layer.CoordinateTransformation = ctFact.CreateFromCoordinateSystems(ProjNet.CoordinateSystems.GeographicCoordinateSystem.WGS84, ProjNet.CoordinateSystems.ProjectedCoordinateSystem.WebMercator);
layer.ReverseCoordinateTransformation = ctFact.CreateFromCoordinateSystems(ProjNet.CoordinateSystems.ProjectedCoordinateSystem.WebMercator, ProjNet.CoordinateSystems.GeographicCoordinateSystem.WGS84);
//SharpMap.Layers.TileLayer layerBackground = new TileLayer(new BingTileSource(BingRequest.UrlBing, "", BingMapType.Aerial), "TileLayer");
SharpMap.Layers.TileLayer layerBackground = new TileLayer(new GoogleTileSource(GoogleMapType.GoogleMap), "googlemaps");
_map.Layers.Add(layerBackground);
_map.Layers.Add(layer);
_map.BackColor = Color.White;
//-98.526890,29.411539
_map.Center = new GeoAPI.Geometries.Coordinate(0,0);
return _map;
Even if I manually give Geo Coordinates It just points to the same spot in the sea.
Please see the below Google map Geo point, this is the point where my map shows as centre. Every time I generate no matter what I do it shows this point as its centre.
71.946088, -3.956171
Any help is much appreciated. Thanks and Cheers!
I found the problem for Google map layer not centring.
The reason is that I used QGIS to convert my ESRI shapefile from WGS84(EPSG:4326) format to Spherical Mercator(EPSG:900913) and it changed the coordinates format but
Google Maps use Google Maps Global Mercator (Spherical Mercator).
When I used an online converter to test this out which you can find here. When I gave the resulting coordinates, it worked out just fine. Now all I have to do is find a way to convert Google Maps Global Mercator (Spherical Mercator).
Thanks for your help #pauldendulk.
I was running into the same problem and in theirExamples they provide a LatLongToGoogle transformation function
public static ICoordinateTransformation LatLonToGoogle()
{
CoordinateSystemFactory csFac = new CoordinateSystemFactory();
CoordinateTransformationFactory ctFac = new CoordinateTransformationFactory();
IGeographicCoordinateSystem sourceCs = csFac.CreateGeographicCoordinateSystem(
"WGS 84",
AngularUnit.Degrees,
HorizontalDatum.WGS84,
PrimeMeridian.Greenwich,
new AxisInfo("north", AxisOrientationEnum.North),
new AxisInfo("east", AxisOrientationEnum.East));
List<ProjectionParameter> parameters = new List<ProjectionParameter>
{
new ProjectionParameter("semi_major", 6378137.0),
new ProjectionParameter("semi_minor", 6378137.0),
new ProjectionParameter("latitude_of_origin", 0.0),
new ProjectionParameter("central_meridian", 0.0),
new ProjectionParameter("scale_factor", 1.0),
new ProjectionParameter("false_easting", 0.0),
new ProjectionParameter("false_northing", 0.0)
};
IProjection projection = csFac.CreateProjection("Google Mercator", "mercator_1sp", parameters);
IProjectedCoordinateSystem targetCs = csFac.CreateProjectedCoordinateSystem(
"Google Mercator",
sourceCs,
projection,
LinearUnit.Metre,
new AxisInfo("East", AxisOrientationEnum.East),
new AxisInfo("North", AxisOrientationEnum.North));
ICoordinateTransformation transformation = ctFac.CreateFromCoordinateSystems(sourceCs, targetCs);
return transformation;

Get polygons within polygons in Google maps

With the help of #Dr.Molle answer I learnt to do free hand drawing in Google maps. Now I'm trying to get the polygon drawn within a polygon something like in the below SS
I want to get the polygons marked in yellow and green within the black.
I'm not sure whether this is possible or not. Please shed some light on this issue.
Updates: on further research I learnt about a method called containsLocation(point, polygons) which is used to find whether the given lat/lng point is within the polygon or not.
But sadly there is no default method to check polygons within polygon provided by Google maps :(
You can check if a polygon is within another polygon by looping through each point of the inner polygon and testing if it is contained within the outer polygon using containsLocation().
var isPolygonInsidePolygon = function (innerPolygon, outerPolygon) {
var pointsInside = 0;
var pointsOutside = 0;
innerPolygon.getPath().getArray().map(function (x) {
(google.maps.geometry.poly.containsLocation(x, outerPolygon)) ? pointsInside++ : pointsOutside++;
});
return (pointsOutside > 0) ? false : true;
};
The JavaScript map() function may not work in older browsers, IE8 or lower.
This is a GIS question. Google Maps API isn't really a full-blown GIS. If you want an open-source solution, I suggest loading your yellow and green polygons into a PostGIS database. Then you can query the database.
As an example, you can encode the drawn polygon as a POLYGON object which has the format:
POLYGON((lon lat, lon lat, lon lat, lon lat, ... lon lat))
And then send that to a PHP file from javascript like (you'll wrap this in a $.get() command or similar and return json results:
getParcels.php?bounds=POLYGON((lon lat, lon lat, lon lat, lon lat, ... lon lat))
In the PHP file, query the PostGIS database and return the ids of the yellow and green polygons:
<?php
$pgcon = pg_connect ("dbname=gis user=gisuser connect_timeout=5") or die ( 'Can not connect to PG server' );
if (!$pgcon) {
echo "No connection to GIS database.\n";
}
$bounds = urldecode($_GET["bounds"];
$ewkt = 'SRID=4326;' . $bounds);
$json = ''; // this will contain your output
// Here I am returning the polygon geometry and the parcelID...
$query .= <<<EOD
SELECT
ST_AsGeoJSON(the_geom) as geom,
parid
FROM
parcels
WHERE
ST_Intersects(the_geom, ST_GeomFromEWKT( $1 ));
EOD;
$result = pg_query_params($pgcon, $query, array($ewkt));
if($result) {
$json = '{"type":"FeatureCollection", "features":[';
while($row = pg_fetch_assoc($result)) {
$json .= '{"geometry":' . $row['geom'] . ',';
$json .= '"type":"Feature","properties":{"parid":"' . $row['parid'] . '"}},';
}
$json = substr($json, 0,-1).']}';
}
echo $json;
?>
This will return the parcels that intersect your polygon using the ST_Intersects command in PostGIS.
An alternative implementation working from #chris-smith solution that might be faster, since it doesn't keep looping if it finds an outside point:
function isPolygonInsidePolygon( innerPolygon, outerPolygon ) {
var points = innerPolygon.getPath().getArray();
for( var i = 0; i < points.length; i++ ){
if( ! google.maps.geometry.poly.containsLocation( points[i], outerPolygon) ){
return false;
}
}
return true;
}

Convert Eastings/ Northings to Longitude/ Latitude?

I have a database of postcodes with Eastings/ Northings, is there a php script that can convert these values so I can use them on google maps?
Can I loop through the database and change each value?
Many thanks
Here is an API I wrote to do exactly this:
https://www.getthedata.com/bng2latlong
Syntax:
https://api.getthedata.com/bng2latlong/[easting]/[northing]
Example:
https://api.getthedata.com/bng2latlong/529090/179645
Some very basic PHP code might look like this:
$easting = 529090;
$northing = 179645;
$json = file_get_contents("https://api.getthedata.com/bng2latlong/$easting/$northing");
$arr = json_decode($json, true);
$latitude = $arr['latitude'];
$longitude = $arr['longitude'];

Getting all polygon coordinates of specific area of image? [closed]

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 10 years ago.
Improve this question
I have an image were I put links and text with html image map. That works fine. I would like to have some hover effect on specific areas of the image. For example take a world map and when you hover over a country that one get highlighted. With the html image map and some css it is not a problem, that is, if you have a list of all polygon coordinates of all countries.
So how do I get those? You cant possibly do that manually.
I am not a photoshop expert but I imagine you would do a "magic wand" selection on an area and then somehow list the coordinates that is used to create the selection. Is there such functionality?
I personally use Paint.Net for simple image editing and it does not have that feature that I know of.
Do you know the way to do this?
I'll tell you how to do it with JavaScript, since this is a programming Q/A site.
To get the rectangular coordinates of the selection bounds is easiest:
#target photoshop
// Save the current unit preferences (optional)
var startRulerUnits = app.preferences.rulerUnits
var startTypeUnits = app.preferences.typeUnits
// Set units to PIXELS
app.preferences.rulerUnits = Units.PIXELS
app.preferences.typeUnits = TypeUnits.PIXELS
// Use the top-most document
var doc = app.activeDocument;
var coords = doc.selection.bounds;
// Write coords to textfile on the desktop. Thanks krasatos
var f = File( '~/Desktop/coords.txt' );
f.open( 'w' );
f.write( coords );
f.close();
// Reset to previous unit prefs (optional)
app.preferences.rulerUnits = startRulerUnits;
app.preferences.typeUnits = startTypeUnits;
This will give the rectangular bounds (think of the bounding box you see when transforming) of the selection in the current active document. It outputs in the order minX, minY, maxX, maxY. This should be enough info to translate to CSS coordinates.
To get the coordinates of individual polygon points you can make the selection into a path and output each pathPoint.anchor on the path using this script:
#target photoshop
// Save the current unit preferences (optional)
var startRulerUnits = app.preferences.rulerUnits
var startTypeUnits = app.preferences.typeUnits
// Set units to PIXELS
app.preferences.rulerUnits = Units.PIXELS
app.preferences.typeUnits = TypeUnits.PIXELS
// Use the top-most document
var doc = app.activeDocument;
// Turn the selection into a work path and give it reference
doc.selection.makeWorkPath();
var wPath = doc.pathItems['Work Path'];
// This will be a string with the final output coordinates
var coords = '';
// Loop through all path points and add their anchor coordinates to the output text
for (var i=0; i<wPath.subPathItems[0].pathPoints.length; i++) {
coords += wPath.subPathItems[0].pathPoints[i].anchor + "\n";
}
// Write coords to textfile on the desktop. Thanks krasatos
var f = File( '~/Desktop/coords.txt' );
f.open( 'w' );
f.write( coords );
f.close();
// Remove the work path
wPath.remove();
// Reset to previous unit prefs (optional)
app.preferences.rulerUnits = startRulerUnits;
app.preferences.typeUnits = startTypeUnits;
Instructions:
-open your map image
-make a selection of the region using your favorite selection tool
-run the script with the extendscript toolkit or by choosing File>Scripts>Browse... and select the .jsx file where the script is saved.
there isn't any option in ps you have to make coordinates in Dreamweaver.