How to embed a google map with a changeable area? - php

I haven't worded this very well
But basically, I'd like to embed a map on my site - but the area it shows will change. I've tried doing this, but it never seems to work as it will focus on the wrong area - the old area, rather than the new area.
Basically, I'd like a google map code that uses $place as a location.
Thanks.

// Prepare your coordinates
var latlng1 = new google.maps.LatLng(0.0, 0.0);
var latlng2 = new google.maps.LatLng(100.0, 100.0);
// Initialize your map
var map = new google.maps.Map(document.getElementById('map'), options);
var options = {
zoom: 6,
center: latlng1,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
// Recenter the map/viewport
map.setCenter(latlng2);

If you don't have the location geocoded, you can look up by address like so: (assume you include your api key above this call - add in the lang vars to output value, in 2 places)
<script type="text/javascript">
$(document).ready(function() {
document.onunload = "GUnload()";
if (GBrowserIsCompatible()) {
var map = new GMap2(document.getElementById("map_canvas"));
map.setCenter(new GLatLng(0.0, 0.0), 13);
// map.setUIToDefault();
geocoder = new GClientGeocoder();
if (geocoder) {
geocoder.getLatLng( '$place', function(point) {
if (!point) {
} else {
var topRight = new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(10,10));var bottomRight = new GControlPosition (G_ANCHOR_BOTTOM_RIGHT, new GSize(10,10));
var mapTypeControl = new GMapTypeControl(); map.addControl(mapTypeControl, topRight);
map.addControl(new GSmallMapControl()); var bounds = map.getBounds();
map.setCenter(point, 13);
var marker = new GMarker(point);
map.addOverlay(marker);
GEvent.addListener(marker, 'click', function() { marker.openInfoWindowHtml('Get Directions ยป' );})
;}
}
);
}
// end geocoding
}
});
</script>

Related

Google Map contain location function with foreach and mysql

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

Removing marker by latitude/longitude in google maps

I have set of markers in my google map. And at the right side of my map I have list of places marked in the map. Now upon clicking the places the color of the pin/marker should be changed. For this I thought I would delete the marker with latitude and longitude(which I will get on clicking the places link) and place a new marker with new image. But I dont know how to delete a marker with latitude and longitude or by place. Please help.
<script type='text/javascript'>
$(document).ready(function() {
var map = null;
var infowindow = new google.maps.InfoWindow();
function createMarker(place) {
var marker = new google.maps.Marker({
map: map
});
var address = place.formatted_address;
marker.setPosition(place.geometry.location);
marker.setTitle(address);
marker.setVisible(true);
address = address + 'B <a class="link" href="#" title="Want to go" alt="' + address + '">W</a> <a class="link" href="#" alt="' + address + '" title="Favourite">F</a>';
$('#trip_location').append(address);
google.maps.event.addListener(marker, 'click', function(e) {
infowindow.setContent('<div><strong>' + marker.title + '</strong><br>');
infowindow.open(map, marker);
});
google.maps.event.trigger(marker, 'click');
}
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(-33.8688, 151.2195),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map_canvas'),
mapOptions);
var input = /** #type {HTMLInputElement} */(document.getElementById('searchTextField'));
var autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.bindTo('bounds', map);
google.maps.event.addListener(autocomplete, 'place_changed', function() {
infowindow.close();
input.className = '';
var place = autocomplete.getPlace();
if (!place.geometry) {
// Inform the user that the place was not found and return.
input.className = 'notfound';
return;
}
var location = place.geometry.location;
var address = place.formatted_address;
createMarker(place);
});
}
$('#trip_location').on('click', '.link', function(e) {
e.preventDefault();
var location = $(this).attr('alt');
});
$('.clear').click(function() {
$('#searchTextField').val('');
});
google.maps.event.addDomListener(window, 'load', initialize);
});
I will be adding multiple markers to google map through google's autocomplete. And the places of the markers will be listed on the right side of the page. When the user clicks the places, it should replace the marker icon.
Instead of deleting and replacing, you could keep a reference to each marker that is associated with a place and just call setIcon on it passing the new setting. See documentation: https://developers.google.com/maps/documentation/javascript/reference#Marker
EDIT: New code in question.
Added markers array to contain the markers, used data attribute to hold marker id, pull markerid attribute value when link element click event is fired.
NOTE: Not tested, so it may be buggy.
$(document).ready(function() {
var map = null;
var markers = [];
var infowindow = new google.maps.InfoWindow();
function createMarker(place) {
var marker = new google.maps.Marker({
map: map
});
var address = place.formatted_address;
marker.setPosition(place.geometry.location);
marker.setTitle(address);
marker.setVisible(true);
markers.push(marker);
address = address + 'W <a class="link" href="#" alt="' + address + '" title="Favourite" data-markerid='" + (markers.length - 1) + "'>F</a>';
$('#trip_location').append(address);
google.maps.event.addListener(marker, 'click', function(e) {
infowindow.setContent('<div><strong>' + marker.title + '</strong><br>');
infowindow.open(map, marker);
});
google.maps.event.trigger(marker, 'click');
}
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(-33.8688, 151.2195),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map_canvas'),
mapOptions);
var input = /** #type {HTMLInputElement} */(document.getElementById('searchTextField'));
var autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.bindTo('bounds', map);
google.maps.event.addListener(autocomplete, 'place_changed', function() {
infowindow.close();
input.className = '';
var place = autocomplete.getPlace();
if (!place.geometry) {
// Inform the user that the place was not found and return.
input.className = 'notfound';
return;
}
var location = place.geometry.location;
var address = place.formatted_address;
createMarker(place);
});
}
$('#trip_location').on('click', '.link', function(e) {
e.preventDefault();
var location = $(this).attr('alt');
var markerid = $(this).data('markerid');
var marker = markers[markerid];
});
$('.clear').click(function() {
$('#searchTextField').val('');
});
google.maps.event.addDomListener(window, 'load', initialize);
});

Reverse Geocode On Google Maps api v3

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>

google map two markers on one map

Hey. I'mm trying to put two points on a single map with same div id..
but it doesn't work..
code:
for 1st,
var map = new GMap2(document.getElementById("map-canvas"));
map.addControl(new GLargeMapControl());
map.addControl(new GMapTypeControl());
map.setCenter(new GLatLng(<?=$lat;?>,<?=$lng;?>), 6);
var point = new GLatLng(<?=$lat;?>,<?=$lng;?>);
var marker = createMarker(point,'Welcome:<b></b><br>Second Info Window with an image<br><img src="http://localhost/gps/user_photo/" width=80 height=80>')
map.addOverlay(marker);
function createMarker(point,html) {
var marker = new GMarker(point);
GEvent.addListener(marker, "click", function() {
marker.openInfoWindowHtml(html);
});
return marker;
}
for 2nd,
var map = new GMap2(document.getElementById("map-canvas"));
map.addControl(new GLargeMapControl());
map.addControl(new GMapTypeControl());
map.setCenter(new GLatLng(<?=$mylat;?>,<?=$mylng;?>), 6);
var point1 = new GLatLng(<?=$mylat;?>,<?=$mylng;?>);
var marker = createMarker1(point1,'Welcome:<b></b><br>Second Info Window with an image<br><img src="http://localhost/gps/user_photo/" width=80 height=80>')
map.addOverlay(marker);
function createMarker1(point,html) {
var marker = new GMarker(point);
GEvent.addListener(marker, "click", function() {
marker.openInfoWindowHtml(html);
});
return marker;
}
why two points not shown in one map?????
and it will seen in two different maps...
//set up map as before
var point0 = new GLatLng(<?=$mylat0;?>,<?=$mylng0;?>);
var point1 = new GLatLng(<?=$mylat1;?>,<?=$mylng1;?>);
var marker0 = createMarker(point0,'Welcome:<b></b><br>First Info Window etc);
var marker1 = createMarker(point1,'Welcome:<b></b><br>Second Info Window etc);
map.addOverlay(marker);
// only declare this once
function createMarker(point,html) {
var marker = new GMarker(point);
GEvent.addListener(marker, "click", function() {
marker.openInfoWindowHtml(html);
});
return marker;
}
This is one way of doing it just to get it working for you, but essentially the js points and markers should be arrays which you loop through - ditto probably the $mylat and $mylong vars in PHP.
As i understood - you want to add two points on one map, on the one page.
If so - you don't need to initialize Gmap twice, just do something like this:
http://pastebin.com/BtvdfaiP

Google Maps API v3 - PHP - MYSQL

GOOGLE MAPS API V3 is what i'm trying to use.
I have all the coordinates in mysql. I just, for example, need to take 5 listings and put them on a map but I'd like to be able to find the center point based on the multiple coordinates I'd like to display, and the zoom level as well. Yeah know?
I'm having the time of my life with something that I know is terribly simple, I just can't figure this API out. I'll paypal $20 to anyone who can help me.
//select * from mysql limit 5
//ok great we got 5 results, great job, format the 5 results so google maps like it, [name,lat,lng] whatever.
//put them on the map and let them be clickable so i can put stuff in the infowindow thing
//make the map adjust to the proper zoom level and center point
UPDATE
This is what i was looking for, hope this helps others.
credit to [Chris B] for the common sense math formula for getting the center coord, the sw cord is the lowest lat and lon, and the ne coord is the greatest lat and lon
sort($lat)&&sort($lon);
$r['c'] = array_sum($lat)/count($lat).', '.array_sum($lon)/count($lon);
$r['ne'] = $lat[count($lat)-1].', '.$lon[count($lon)-1];
$r['sw'] = $lat[0].', '.$lon[0];
var myOptions = {zoom:4,center: new google.maps.LatLng(<?php echo $r['c']; ?>),mapTypeId:google.maps.MapTypeId.ROADMAP}
var map = new google.maps.Map(document.getElementById("map_canvas"),myOptions);
<?php foreach($x as $l) echo 'new google.maps.Marker({position:new google.maps.LatLng('.$l['lat'].','.$l['lon'].'),map:map,clickable:true});'; ?>
map.fitBounds(new google.maps.LatLngBounds(new google.maps.LatLng(<?php echo $r['sw']; ?>),new google.maps.LatLng(<?php echo $r['ne']; ?>)));
If an average/weighted center point is acceptable - you could just average all the latitudes, and average all the longitudes:
$latTotal = 0;
$lngTotal = 0;
foreach ($markers as $marker) {
$latTotal += $marker['lat'];
$lngTotal += $marker['lng'];
}
$centerLat = $latTotal/count($markers);
$centerLng = $lngTotal/count($markers);
For the rest of it, there are some good V3 tutorials on Google.
I was using Google Maps v3 a month or two back, but switched to v2 later on. However, I had the same problem as you so I wrote a MarkerManager class for API v3. I can't find the latest version of my class, but I did find a, hopefully, working one. You can get it here.
I have to warn you though - it's not optimazed at all and is not using overlays, so when I tried putting 50+ markers in the manager and toggled the hide/show the class is sloooow... But maybe you can have some success with it.
Usage example:
var map = new google.maps.Map(document.getElementById('MapLayerId'), {
zoom: 7,
position: new google.maps.LatLng(latitude, longitude),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var marker1 = new google.maps.Marker({
position: new google.maps.LatLng(latitude, longitude),
map: map
});
var marker2 = new google.maps.Marker({
position: new google.maps.LatLng(latitude, longitude),
map: map
});
var manager = new MarkerManager(map, {fitBounds: true});
manager.add(marker1);
manager.add(marker2);
manager.show();
GDownloadUrl in V2 equivalent downloadUrl in GOOGLE MAPS API V3
How to load all the coordinates in database(Mysql or Sql).
var myLatlng = new google.maps.LatLng("37.427770" ,"-122.144841");
var myOptions = {zoom: 15, center: myLatlng, mapTypeId: google.maps.MapTypeId.ROADMAP,}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var url='marker.php?arg1=x&arg2=y...';
downloadUrl(url, function(data) {
var markers = data.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var latlng = new google.maps.LatLng(parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var marker = new google.maps.Marker({position: latlng, map: map});
}
});
function createXmlHttpRequest() {
try {
if (typeof ActiveXObject != 'undefined') {
return new ActiveXObject('Microsoft.XMLHTTP');
} else if (window["XMLHttpRequest"]) {
return new XMLHttpRequest();
}
} catch (e) {
changeStatus(e);
}
return null;
};
function downloadUrl(url, callback) {
var status = -1;
var request = createXmlHttpRequest();
if (!request) {
return false;
}
request.open('GET', url);
request.onreadystatechange = function() {
if (request.readyState == 4) {
try {
status = request.status;
} catch (e) {
// Usually indicates request timed out in FF.
}
if (status == 200) {
var s=request.responseText;
callback( xmlParse(s) );
}
}
}
try {
request.send(null);
}catch (e) {
changeStatus(e);
}
};
function xmlParse(str) {
if (typeof ActiveXObject != 'undefined' && typeof GetObject != 'undefined') {
var doc = new ActiveXObject('Microsoft.XMLDOM');
doc.loadXML(str);
return doc;
}
if (typeof DOMParser != 'undefined') {
return (new DOMParser()).parseFromString(str, 'text/xml');
}
return createElement('div', null);
}
Have you checked out the official google map PHP/Mysql tutorial?
http://code.google.com/apis/maps/articles/phpsqlajax.html
Try this algorithm for finding the centroid of a polygon:
http://tog.acm.org/resources/GraphicsGems/gemsiv/centroid.c

Categories