How to show multiple areas by location in google maps using php - php

Here is the Initialise function.....
function initialize() {
Here the variables $Latitude,$Longitude are array values so how can i store them in Javascript Variables so that they can store the above array values....
var lat='<?php echo $Latitude?>';
var lon='<?php echo $Longitude?>';
var latlng = new google.maps.LatLng(lat,lon);
var myOptions = {
zoom: 10,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
Here how can i loop the geocoder to show multiple areas using above array variables...
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
geocoder = new google.maps.Geocoder();
var marker = new google.maps.Marker({
position: latlng,
map: map,
title: "Hello World!"
});
}

Its my sample code to plot multiple areas in google map by using area name or lat,lng.
var map;
var geocoder;
var marker;
var people = new Array();
var latlng;
var infowindow;
$(document).ready(function() {
ViewCustInGoogleMap();
});
function ViewCustInGoogleMap() {
var mapOptions = {
center: new google.maps.LatLng(11.0168445, 76.9558321), // Coimbatore = (11.0168445, 76.9558321)
zoom: 7,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
// Get data from database. It should be like below format or you can alter it.
var data = '[{ "DisplayText": "adcv", "ADDRESS": "Jamiya Nagar Kovaipudur Coimbatore-641042", "LatitudeLongitude": "10.9435131,76.9383790", "MarkerId": "Customer" },{ "DisplayText": "abcd", "ADDRESS": "Coimbatore-641042", "LatitudeLongitude": "11.0168445,76.9558321", "MarkerId": "Customer"}]';
people = JSON.parse(data);
for (var i = 0; i < people.length; i++) {
setMarker(people[i]);
}
}
function setMarker(people) {
geocoder = new google.maps.Geocoder();
infowindow = new google.maps.InfoWindow();
if ((people["LatitudeLongitude"] == null) || (people["LatitudeLongitude"] == 'null') || (people["LatitudeLongitude"] == '')) {
geocoder.geocode({ 'address': people["Address"] }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
latlng = new google.maps.LatLng(results[0].geometry.location.lat(), results[0].geometry.location.lng());
marker = new google.maps.Marker({
position: latlng,
map: map,
draggable: false,
html: people["DisplayText"],
icon: "images/marker/" + people["MarkerId"] + ".png"
});
//marker.setPosition(latlng);
//map.setCenter(latlng);
google.maps.event.addListener(marker, 'click', function(event) {
infowindow.setContent(this.html);
infowindow.setPosition(event.latLng);
infowindow.open(map, this);
});
}
else {
alert(people["DisplayText"] + " -- " + people["Address"] + ". This address couldn't be found");
}
});
}
else {
var latlngStr = people["LatitudeLongitude"].split(",");
var lat = parseFloat(latlngStr[0]);
var lng = parseFloat(latlngStr[1]);
latlng = new google.maps.LatLng(lat, lng);
marker = new google.maps.Marker({
position: latlng,
map: map,
draggable: false, // cant drag it
html: people["DisplayText"] // Content display on marker click
//icon: "images/marker.png" // Give ur own image
});
//marker.setPosition(latlng);
//map.setCenter(latlng);
google.maps.event.addListener(marker, 'click', function(event) {
infowindow.setContent(this.html);
infowindow.setPosition(event.latLng);
infowindow.open(map, this);
});
}
}
<script src="http://code.jquery.com/jquery-1.10.2.min.js" type="text/javascript"></script>
<script src="http://maps.googleapis.com/maps/api/js?key=AIzaSyA7IZt-36CgqSGDFK8pChUdQXFyKIhpMBY&sensor=true" type="text/javascript"></script>
<div id="map-canvas" style="width: 800px; height: 500px;">
</div>

This should work for you assuming lat and lon are javascript arrays with the same length:
var map = null;
function initialize() {
var lat='<?php echo $Latitude?>';
var lon='<?php echo $Longitude?>';
// initialize map center on first point
var latlng = new google.maps.LatLng(lat[0],lon[0]);
var myOptions = {
zoom: 10,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var bounds = new google.maps.LatLngBounds();
for (var i=0, i<lat.length; i++) {
var latlng = new google.maps.LatLng(lat[i],lon[i]);
bounds.extend(latlng);
var marker = new google.maps.Marker({
position: latlng,
map: map,
title: "Hello World!"
});
}
// zoom and center the map to show all the markers
map.fitBounds(bounds);
}

<?php
/* lat/lng data will be added to this array */
try{$work=$_GET["service"];}catch(Exception $e){echo 'Authorization Failed.Map may Misbehave or Buggy.Click here to report this';}
$locations=array();
$uname="root";
$pass="";
$servername="localhost";
$dbname="bcremote";
$db=new mysqli($servername,$uname,$pass,$dbname);
$query = $db->query('SELECT * FROM location');
while( $row = $query->fetch_assoc() ){
$name = $row['uname'];
$longitude = $row['longitude'];
$latitude = $row['latitude'];
/* Each row is added as a new array */
$locations[]=array( 'name'=>$name, 'lat'=>$latitude, 'lng'=>$longitude );
}
//echo $locations[0]['name'].": In stock: ".$locations[0]['lat'].", sold: ".$locations[0]['lng'].".<br>";
//echo $locations[1]['name'].": In stock: ".$locations[1]['lat'].", sold: ".$locations[1]['lng'].".<br>";
?>
<script>
//var myLatLng = {lat: -25.363, lng: 131.044};
function initMap() {
var myLatLng = {lat: -25.363, lng: 131.044};
var map = new google.maps.Map(document.getElementById('map'), {
center: myLatLng,
scrollwheel: false,
zoom: 4
});
<?php for($i=0;$i<sizeof($locations);$i++)
{ ?>
var marker = new google.maps.Marker({
map: map,
position: {lat: <?php echo $locations[$i]['lat']?>,lng: <?php echo $locations[$i]['lng']?>},
title: 'Service'
});
<?php } ?>
}
</script>
This code Snippet uses Dynamic Content without using JSON or XML. This below code is what we see in the Browser View Source tool. Hope this helps you...
<script>
//var myLatLng = {lat: -25.363, lng: 131.044};
function initMap() {
var myLatLng = {lat: -25.363, lng: 131.044};
var map = new google.maps.Map(document.getElementById('map'), {
center: myLatLng,
scrollwheel: false,
zoom: 4
});
var marker = new google.maps.Marker({
map: map,
position: {lat: 192.652.231.25,lng: 192.652.231.25},
title: 'Service'
});
var marker = new google.maps.Marker({
map: map,
position: {lat: 192.652.231.25,lng: 192.652.231.25},
title: 'Service'
});
}
</script>

UPDATE 2017
Google maps now supports the creation of maps with multiple locations which you can embed via iframe! Source: https://www.create.net/support/218-how-to-pin-point-multiple-locations-on-google-maps.html
Go to https://www.google.com/maps
Make sure you're signed in - you can do so by clicking the Login button in the top-right corner.
In the top left corner, next to the search box, click the menu icon to expand the menu
Click "Your Places", "Maps" and then click "Create Map" to edit your map.
A new window will pop up. Give your map a title and description, then click "Save".
You can now pinpoint locations manually by clicking the marker icon and placing it directly onto the map, or search for locations using the search box at the top of the screen.
If you're adding locations manually, you can name the location and save to add it to the map. If you're searching and adding specific locations, a green marker will appear on the map and you can click the 'Add to map' link.
Repeat steps 6 and 7 for each location you wish to plot.
Once you have done that save your map again and refresh the page. Then, to get the code to embed your map on to your Create website, please follow these steps:
Make sure you map is public. You can do this by clicking 'Share' beneath the map name.
Under 'Who has access' click 'Change' and make turn it 'On - Public on the web' and save.
Next, click the menu icon and click on the link 'Embed on my site'
The code will then pop up in a new window.
To use this, you will need to paste the code into an HTML fragment on your Create account, and then place the HTML fragment on your chosen page.
Example:
<iframe src="https://www.google.com/maps/d/embed?mid=1tX88xmVMIFW9DQneDff_ZMJtekc" width="100%" height="480"></iframe>

Related

Change the color of one of the pin on google map in PHP

My code is as below `
<script type="text/javascript">
var locations = [
['add1', lat1, long1],
['add2', lat2, long2],
['add3', lat3, long3],
];
var map = new google.maps.Map(document.getElementById('map'), {
zoom:10,
center: new google.maps.LatLng(18.528771, 73.906314),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < locations.length; i++) {
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));
}
</script>`
More than one pins are there on map, I would like to display one of the pin in diff color or display an image instead of bubble.
I am implementing the code in PHP.
You need add an icon attribute to the marker options and set the image to the correct google pin:
var image = 'images/beachflag.png';
var myLatLng = new google.maps.LatLng(-33.890542, 151.274856);
var beachMarker = new google.maps.Marker({
position: myLatLng,
map: map,
icon: image
});
see google doc google example

Inserting varianble GPS coordinates in google maps

I want my script to get the latitude and longittude coordinates from a GPS(mobile phone) and then insert them into a google map and display the location of the Mobile phone. Well , i am able to retrieve the Lat,Long coordinates from the GPS but it won't insert them as the çentre'of the map displayed. My code :
<script>
$(document).ready(function(){
navigator.geolocation.getCurrentPosition(useposition);
});
function useposition(position){
lat = position.coords.latitude;
lon = position.coords.longitude;
$("#location").html('Lat: ' + lat + '<br />Lon: ' + lon);
}
</script><meta name="viewport" content="initial-scale=1.0, user-scalable=no"<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script><script type="text/javascript">
function initialize() {
var latlng = new google.maps.LatLng(54,-1);
var settings = {
zoom: 15,
center: latlng,
mapTypeControl: true,
mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
navigationControl: true,
navigationControlOptions: {style: google.maps.NavigationControlStyle.SMALL},
mapTypeId: google.maps.MapTypeId.ROADMAP }; var map = new google.maps.Map(document.getElementById("map"), settings);
var marker = new google.maps.Marker({ position: latlng, map: map, title:"Yeah buddy!" })};
</script>
As You can see i Fetch the GPs coordinates and i want to insert them in my map which i load with :<body onload="initialize ()" > </body>
I just do not know how to make a variable from lat,lon and how to insert it properly in gogle maps . Help me please.
I assume by 'insert coordinates into the map' you mean add a marker at that location?
The first problem you'll have is your map variable is a local variable to your initialize function. So you could make that a global variable. Then in your useposition function you can simply create a new marker.
<script>
var map;
$(document).ready(function(){
navigator.geolocation.getCurrentPosition(useposition);
});
function useposition(position){
lat = position.coords.latitude;
lon = position.coords.longitude;
$("#location").html('Lat: ' + lat + '<br />Lon: ' + lon);
var marker = new google.maps.Marker({
position: new google.maps.LatLng(lat,lon),
map: map,
title:"Your Mobile" });
}
function initialize() {
var latlng = new google.maps.LatLng(54,-1);
var settings = {
zoom: 15,
center: latlng,
mapTypeControl: true,
mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
navigationControl: true,
navigationControlOptions: {style: google.maps.NavigationControlStyle.SMALL},
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map"), settings);
var marker = new google.maps.Marker({ position: latlng, map: map, title:"Yeah buddy!" })
};
</script>

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>

Getting error when trying to pass values from array to Google Maps Object

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
});

Google Maps V3 Zoom to Show all markers not working

I'm using Google Maps V3 API and after creating several markers on the map, I am having difficulty getting the map to zoom out such that it shows all markers. Right now the code below just shows the markers without adjusting the zoom. Can you find the mistake in there? Thanks!
<script type="text/javascript">
function initialize() {
var latlng = new google.maps.LatLng(1.289566,103.847267);
var options = {
zoom: 15,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
scrollwheel: false
};
var map = new google.maps.Map(document.getElementById('map_canvas'), options);
var marker = new google.maps.Marker({
position: new google.maps.LatLng(1.289566,103.847267),
map: map,
icon: "http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=1|ff776b"
});
var marker = new google.maps.Marker({
position: new google.maps.LatLng(1.301224,103.912949),
map: map,
icon: "http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=2|ff776b"
});
var marker = new google.maps.Marker({
position: new google.maps.LatLng(1.293150,103.827164),
map: map,
icon: "http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=3|ff776b"
});
var LatLngList = array (
new google.maps.LatLng(1.289566,103.847267),
new google.maps.LatLng(1.301224,103.912949),
new google.maps.LatLng(1.293150,103.827164)
);
var bounds = new google.maps.LatLngBounds();
for (var i = 0, LtLgLen = LatLngList.length; i < LtLgLen; i++) {
bounds.extend(LatLngList[i]);
}
map.fitBounds(bounds);
}
</script>
This:
var LatLngList = array (
new google.maps.LatLng(1.289566,103.847267),
new google.maps.LatLng(1.301224,103.912949),
new google.maps.LatLng(1.293150,103.827164)
);
is not how you create an array in JavaScript. Instead, try:
var LatLngList = [
new google.maps.LatLng(1.289566,103.847267),
new google.maps.LatLng(1.301224,103.912949),
new google.maps.LatLng(1.293150,103.827164)
];
Where you are defining LatLngList you have an error. The proper code should be:
var LatLngList = new Array();
Not:
var LatLngList = array();

Categories